3 回答
![?](http://img1.sycdn.imooc.com/54584cde0001d19202200220-100-100.jpg)
TA贡献1873条经验 获得超9个赞
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++;
}
?>
![?](http://img1.sycdn.imooc.com/545868b60001587202200220-100-100.jpg)
TA贡献2011条经验 获得超2个赞
$prepend = 'prepend me please';
$file = '/path/to/file';
$fileContents = file_get_contents($file);
file_put_contents($file, $prepend . $fileContents);
![?](http://img1.sycdn.imooc.com/5458477f0001cabd02200220-100-100.jpg)
TA贡献1824条经验 获得超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);
- 3 回答
- 0 关注
- 434 浏览
添加回答
举报