Find centralized, trusted content and collaborate around the technologies you use most.
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
我有一些超过 1GB 的非常大的文本文件,我经常需要使用 PHP 在文件的顶部/开头添加一行。
我知道该怎么做,但是就内存使用而言,最有效的方法是什么?
您只能在底部有效地添加到文件中。如果您需要添加到顶部,您别无选择,只能重写整个文件。
在不将整个文件读入缓冲区的情况下执行此操作的方法是将数据分块移回,直到顶部有可用空间。
另一种方法(如果您使用 *nix 平台)是使用 PHP 对 cat 和文件重定向进行系统调用,这在内存使用和性能方面比尝试使用 PHP 操作文件头更有效.