EDIT: For anyone else looking for an answer, I used this. Probably the fastest solution to the problem.
Suppose I have a very large test.txt
file containing:
line1
line4
line5
line6
I wish to add line2 and line3 after line1. I use the following code to achieve this:
$file = fopen('test.txt', 'r+');
fseek($file, 5);
fwrite($file, "\r\nline2\r\nline3\r\n");
However, the txt file now becomes, with line4 and line5 being overwritten:
line1
line2
line3
line6
I get the same result with c+
mode in fopen
. I can't use a
or a+
as they just append content to the end of the file. I also can't read the whole file into a string and analyse it to make changes, as this file is really huge.
Any way to fix this problem?
Note: Any solutions that involve reading the whole file as a string and then making changes from there will not be feasible due to the large amount of content in the file. If there are any cheeky workarounds to add content to a few lines between the first and second line, it will be good enough. :D