如何将文件预先开始? [英] How do I prepend file to beginning?

查看:105
本文介绍了如何将文件预先开始?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,如果写入一个文件,它将写入现有文件的结尾。

In PHP if you write to a file it will write end of that existing file.

我们如何在文件的前面添加一个文件?

How do we prepend a file to write in the beginning of that file?

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

I have tried rewind($handle) function but seems overwriting if current content is larger than existing.

任何想法?

推荐答案

对于大文件,file_get_contents解决方案效率低下。此解决方案可能需要更长时间,具体取决于需要预先处理的数据量(更多的是更好),但不会消耗内存。

The file_get_contents solution is inefficient for large files. This solution may take longer, depending on the amount of data that needs to be prepended (more is actually better), but it won't eat up memory.

<?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++;
}
?>

这篇关于如何将文件预先开始?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆