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.
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.
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?
Thanks! I looked around and could not find an answer to this on stackoverflow.
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.