我正在使用PHP和fwrite代码,但是我希望每次写入的位置都从文件的开头开始,而不会擦除其内容。我正在使用这段代码,但它是写在文件的末尾。
$fr = fopen("aaaa.txt", "a");
fwrite($fr, "text");
fclose($fr);
所以你想在文件开头写入新数据,但是要保留原有内容?你需要先获取现有的内容,然后在覆盖新数据后将其追加回文件中。
$file = 'aaaa.txt';
$oldContents = file_get_contents($file);
$fr = fopen($file, 'w');
fwrite($fr, "text");
fwrite($fr, $oldContents);
fclose($fr);
来自 PHP 网站:
注意:
如果您以追加("a" 或 "a+")模式打开文件,则无论文件位置如何,您写入文件的任何数据都将始终被追加。
我建议像这样(来自 php.net 网站):
$handle = fopen('output.txt', 'r+');
fwrite($handle, 'Really long sentence.');
rewind($handle);
fwrite($handle, 'Foo');
rewind($handle);
echo fread($handle, filesize('output.txt'));
fclose($handle);
$file = 'aaaa.txt';
$tmp = file_get_contents($file);
$tmp = 'text'.$tmp;
$tmp = file_put_contents($file, $tmp);
echo ($tmp != false)? 'OK': '!OK';
这应该可以工作:
$file="name.extension";
$current = file_get_contents($file);
$user = $_POST["username"];
$pass = $_POST["password"];
file_put_contents($file,$current . "Whatever you want to add here"
这个程序会找到当前的内容并在每次运行代码时将其复制/粘贴回来(为了让答案尽可能简单易懂,我尝试使它尽可能简单,以防其他答案过于复杂)
$file = 'aaaa.txt';
$oldContents = file_get_contents($file);
$fr = fopen($file, 'w');
$newmsg="text".$oldContents;
fwrite($fr, $oldContents);
fclose($fr);
使用file_get_contents预取旧内容,并在写入新内容后追加它是一种方法。 但是,如果文件正在动态写入,并且在此过程中您需要返回到文件开头并添加一些文本,则可以按照以下方式操作:
$handle = fopen($FILE_PATH, 'w+');
fwrite($handle, "I am writing to a new empty file
and now I need to add Hello World to the beginning");
要在前面添加“Hello World”,请执行以下操作:
$oldText = '';
fseek($handle, 0);
while (!feof($handle)) {
$oldText .= fgets($handle);
}
fseek($handle, 0);
fwrite($handle, "Hello World! ");
fwrite($handle, $oldText);
fclose($handle);
结果将是:
你好,世界!我正在写入一个新的空文件,现在我需要在开头添加“Hello World”
提醒和像Fabrizio已经指出的:
如果您以追加(“a”或“a +”)模式打开文件,则写入文件的任何数据都将始终附加,而不管文件位置如何
在EOF时执行以下步骤
$handler = fopen('1.txt', 'w+');//1
rewind($handler);//3
$prepend = "我想在这个文件的开头添加这段文字";
$chunkLength = strlen($prepend);//2
$i = 0;
do{
$readData = fread($handler, $chunkLength);//4
fseek($handler, $i * $chunkLength);//5
fwrite($handler, $prepend);//6
$prepend = $readData;//7
$i++;
}while ($readData);//8
fclose($handler);
首先以c+模式打开文件,如果文件不存在则创建新文件,并将指针指向文件开头。要获取旧内容,请使用file_get_contents
并检查文件是否存在。
$fh = fopen($file_path, 'c+');
if (file_exists($file_path)) {
$oldContents = file_get_contents($file_path);
fwrite($fh,"New Content" );
fwrite($fh, $oldContents);
} else {
fwrite($fh,"New Content");
}
fclose($fh);
$fr = fopen("aaaa.txt", "r+");
fseek($fr, 0); // this line will set the position to the beginning of the file
fwrite($fr, "text");
fclose($fr);
while(old_file_exists){usleep(1000);}
- Fabrizio