4

I have a large file "file.txt"

I want to read one specific line from the file, change something and then write that line back into its place in the file.

Being that it is a large file, I do not want to read the entire file during the reading or writing process, I only want to access that one line.

This is what I'm using to retrieve the desired line:

$myLine = 100;
$file = new SplFileObject('file.txt');
$file->seek($myLine-1);
$oldline = $file->current();
$newline=str_replace('a','b',$oldline);

Now how do I write this $newline to replace the old line in the file?

Fomo
  • 143
  • 9

1 Answers1

1

You could use this function:

function injectData($file, $data, $position) {
    $temp = fopen('php://temp', "rw+");
    $fd = fopen($file, 'r+b');

    fseek($fd, $position);
    stream_copy_to_stream($fd, $temp); // copy end

    fseek($fd, $position); // seek back
    fwrite($fd, $data); // write data

    rewind($temp);
    stream_copy_to_stream($temp, $fd); // stich end on again

    fclose($temp);
    fclose($fd);
}

I got it from: PHP what is the best way to write data to middle of file without rewriting file

Community
  • 1
  • 1
jankal
  • 1,090
  • 1
  • 11
  • 28