fwrite 从头开始写入而不删除
我正在使用 PHP 和 fwrite 代码,但我希望每个写入位置都从文件的开头开始,而不擦除其内容。我正在使用这段代码,但它正在写入文件末尾。
$fr = fopen("aaaa.txt", "a");
fwrite($fr, "text");
fclose($fr);
I am using PHP and fwrite code, but I want every write position to start from the beginning of the file without erasing it's content. I am using this code but it is writing to the end of the file.
$fr = fopen("aaaa.txt", "a");
fwrite($fr, "text");
fclose($fr);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(9)
那么您想在文件的开头写入,将所有当前内容保留在新数据之后吗?您必须首先获取其现有内容,然后在用新数据覆盖后将其附加回文件中。
如果您想避免将原始文件的内容加载到 PHP 脚本中的内存中,您可以尝试首先写入临时文件,使用循环缓冲区或系统调用将原始文件的内容附加到临时文件中,然后删除原始文件并重命名您的临时文件。
So you want to write at the beginning of a file, leaving all of its current contents after the new data? You'll have to grab its existing contents first, then append it back into the file once you've overwritten with your new data.
If you want to avoid loading the original file's contents into memory in your PHP script, you might try first writing to a temp file, using a loop buffer or system calls to append the contents of your original file to the temp file, then remove the original file and rename your temp file.
来自 PHP 站点:
我建议这样的
From the PHP site:
I suggest something like this (from php.net site):
使用此代码:
use this code :
使用 file_get_contents 预取旧内容并在写入新内容后附加它是一种方法。
但是,如果文件是动态写入的,并且在此过程中您需要返回到文件的开头并添加一些文本,则方法如下:
要在前面添加 Hello World,请执行以下操作:
结果将是:
提醒中,就像 Fabrizio 已经指出的那样:
Prefetching old content with file_get_contents and appending it after writing new content is one way to do it.
But In case, the file is being dynamically written and along the way you needed to go back to the beginning of file and add some text, then here is how:
to prepend Hello World do the following:
The result would be:
Reminder and like Fabrizio already noted:
这应该有效:
这会找到当前的内容,并在每次运行代码时将其复制/粘贴回来(尝试使其尽可能简单,以防其他答案有点太复杂)
This should work:
This finds the current stuff and copy/pastes it back each time the code is ran (tried to make it as simple as possible in case other answers are a little too complicated)
执行这些步骤,而 EOF
do these steps, while EOF
首先以 C+ 模式打开文件,如果文件不存在,则打开文件或创建新文件,并将指针指向文件的开头。要获取旧内容,请使用 file_get_contents 并检查文件是否存在。
First open the file in c+ mode which opens file or create new file if doesnot exists and points the pointer at beginning of the file. To get old content use
file_get_contents
and check if the file exists.使用 fseek() 设置您在文件中的位置。
Use fseek() to set your position in the file.