1

Let's consider we got following format text file with a size around 1Gb:

...
li1
li2
li3
...

My task is to update line li2 to line2.

Following will not work:

$fd = fopen("file", 'c+');

// ..
// code that loops till we reach li2 line..
// ..
$offset = ftell($fd);
// ..

fseek($fd, $offset );
fwrite($fd, "line2" . PHP_EOL);

Since it produces:

...
li1
line2
3
...

I'm expecting to have as result:

...
li1
line2
li3
...

Thanks

2 Answers2

1

In my opinion we need a temporary file here where we copy the non-changed result, add the change and continue with non-changed result. At the end the original file may be renamed and the temp file to take its name.

As I am familiar with file systems you cannot just delete/insert part of the file. Or it is just too complicated and it is not worthy.

Second - you can copy the file in the memory and make your modifications there but here you are resource dependent and your code may not pass on some servers (e.g. dedicated hosting).

Good luck!

Anton Mitsev
  • 602
  • 9
  • 15
-1

If you know what you must change in text just use this:

$file_data=file_get_contents(some_name.txt);
$text = str_replace("line2", "li2", $file_data);
file_put_contents('some_name_changed.txt',  $text);

Or read line by line and load in $text then replace what you want.

stefo91
  • 618
  • 6
  • 16