替换文件中的一行而无需重写整个文件(在PHP中) [英] Replacing a line in a file without rewriting the entire file (in PHP)

查看:92
本文介绍了替换文件中的一行而无需重写整个文件(在PHP中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我说我的文本文件大小适中(〜850kb,10,000多个行)

Lets say I have a modestly sized text file (~850kb, 10,000+ lines)

我想替换散布在文件中的特定行(或几行).

And I want to replace a particular line (or several) spread out amongst the file.

当前执行此操作的方法包括重写整个文件.我当前使用的方法是逐行读取整个文件,写入.tmp文件,完成后,我将tmp文件重命名为原始源文件.

Current methods for doing this include re-writing the whole file. The current method I use is read through the entire file line by line, writing to a .tmp file, and once I am done, I rename() the tmp file to the original source file.

它可以工作,但是速度很慢.当然,随着文件的增加,执行时间也会增加.

It works, but it is slow. And of course, as the file grows, so will execution times.

还有另一种方法(使用PHP)完成工作而不必每次需要替换或删除一行或两行时都重写整个文件吗?

Is there another way (using PHP) to get the job done without having to rewrite the entire file every time a line or two need to be replaced or removed?

谢谢!我环顾四周,在stackoverflow上找不到答案.

Thanks! I looked around and could not find an answer to this on stackoverflow.

推荐答案

如果替换的大小与原始行的大小完全相同,则只需在文件中的该位置fwrite(),就可以了.但是,如果长度不同(较短),则必须重写替换后的文件部分.

If the replacement is EXACTLY the same size as the original line, then you can simply fwrite() at that location in the file and all's well. But if it's a different length (shorter OR longer), you will have to rewrite the portion of the file that comes AFTER the replacement.

无法解决此问题.较短的新"行将在文件中留下空白,而较长的新"行将覆盖下一行的第一部分.

There is no way around this. Shorter 'new' lines will leave a gap in the file, and longer 'new' lines would overwrite the first part of the next line.

基本上,您在问是否可以在不移动原始板的情况下将一块木头插入另一块板的中间.

Basically, you're asking if it's possible to insert a piece of wood in the middle of another board without having to move the original board around.

这篇关于替换文件中的一行而无需重写整个文件(在PHP中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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