php file_put_contents ...可以在开头附加吗?

发布于 2024-10-07 22:12:58 字数 416 浏览 9 评论 0原文

<?php
$file = 'people.txt';
// The new person to add to the file
$person = "John Smith\n";
// Write the contents to the file, 
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
 file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
?>

这会将内容附加到文件末尾。我想在文件的开头写入最新的内容。

<?php
$file = 'people.txt';
// The new person to add to the file
$person = "John Smith\n";
// Write the contents to the file, 
// using the FILE_APPEND flag to append the content to the end of the file
// and the LOCK_EX flag to prevent anyone else writing to the file at the same time
 file_put_contents($file, $person, FILE_APPEND | LOCK_EX);
?>

This will append the content at the end of the file. i want to write newest at the beginning of the file.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

对你的占有欲 2024-10-14 22:12:58

正如手册页所示,没有用于预先添加数据的标志。

您需要首先使用 file_get_contents() 读取整个文件,在前面添加值,然后保存整个字符串。

As the manual page shows, there is no flag to prepend data.

You will need to read the whole file using file_get_contents() first, prepend the value, and save the whole string.

眼眸里的那抹悲凉 2024-10-14 22:12:58

在文件开头写入可能会给文件系统和硬盘带来一些不必要的开销。

作为解决方案,您必须读取内存中的整个文件,写入要添加的新内容,然后写入旧内容。对于大文件,这需要时间和内存(这取决于您的实际工作负载,但一般来说,它很慢)。

正常附加(在末尾)然后向后读取文件是否是一个可行的解决方案?这将导致写入速度更快,但读取速度更慢。这基本上取决于你的工作量:)

writing at the beginning of a file might incur some unnecessary overhead on the file-system and the hard-disk.

As a solution, you would have to read the entire file in-memory, write the new content you want added, and then write the old content. This takes time and memory for large files(it depends on the actual workload you have, but as a general rule, its slow).

Would appending normally(at the end) and then reading the file backwards would be a viable solution? This would lead to faster writes, but slower reads. It basically depends on your workload:)

疯了 2024-10-14 22:12:58

如果您想使用file_put_contents,您将无法选择,您需要读取/连接/写入。

<?php
$file = 'people.txt';  
$appendBefore = 'Go to the beach';
$temp = file_get_contents($file);
$content = $appendBefore.$temp;
file_put_contents($file, $content);

You won't have the choice if you want to use file_put_contents, you'll need to read / contatenate / write.

<?php
$file = 'people.txt';  
$appendBefore = 'Go to the beach';
$temp = file_get_contents($file);
$content = $appendBefore.$temp;
file_put_contents($file, $content);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文