如何将文件预置到开头?

2022-08-30 21:40:55

在PHP中,如果你写到一个文件,它将写出那个现有文件的结尾。

我们如何在文件的开头预置要写入的文件?

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

有什么想法吗?


答案 1
$prepend = 'prepend me please';

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

$fileContents = file_get_contents($file);

file_put_contents($file, $prepend . $fileContents);

答案 2

对于大型文件,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++;
}
?>

推荐