如何将文件添加到开头?

mat*_*hew 14 php file

在PHP中,如果您写入文件,它将写入该现有文件的结尾.

我们如何在该文件的开头添加要写入的文件?

我已尝试过rewind($handle)功能,但如果当前内容大于现有内容,则会覆盖.

有任何想法吗?

ale*_*lex 23

$prepend = 'prepend me please';

$file = '/path/to/file';

$fileContents = file_get_contents($file);

file_put_contents($file, $prepend . $fileContents);
Run Code Online (Sandbox Code Playgroud)


Fra*_*til 14

file_get_contents解决方案对于大文件效率低下.此解决方案可能需要更长时间,具体取决于需要预先添加的数据量(实际上更好),但它不会占用内存.

<?php

$cache_new = "Prepend this"; // this gets prepended
$file = "file.dat"; // the file to which $cache_new gets prepended

$handle = fopen($file, "r+");
$len = strlen($cache_new);
$final_len = filesize($file) + $len;
$cache_old = fread($handle, $len);
rewind($handle);
$i = 1;
while (ftell($handle) < $final_len) {
  fwrite($handle, $cache_new);
  $cache_new = $cache_old;
  $cache_old = fread($handle, $len);
  fseek($handle, $i * $len);
  $i++;
}
?>
Run Code Online (Sandbox Code Playgroud)

  • `file_get_contents()`[docs](http://php.net/manual/en/function.file-get-contents.php)这样说:"...是读取文件内容的首选方式如果操作系统支持,它将使用内存映射技术来提高性能." (2认同)
  • @alex 这仍然意味着它会一次性将整个内容读入内存。Fraxtil 的方法使用的内存很少,但步骤很多。这取决于哪种情况更有效...... (2认同)

mis*_*ima 5

$filename  = "log.txt";
$file_to_read = @fopen($filename, "r");
$old_text = @fread($file_to_read, 1024); // max 1024
@fclose($file_to_read);
$file_to_write = fopen($filename, "w");
fwrite($file_to_write, "new text".$old_text);
Run Code Online (Sandbox Code Playgroud)