如何将文件添加到开头? [英] How do I prepend file to beginning?

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

问题描述

在 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天全站免登陆