5

Perhaps its my english but the explanation in the PHP Manual (quoted bellow) doesn't answer my question quite clearly.

To move to a position before the end-of-file, you need to pass a negative value in offset and set whence to SEEK_END.

I have a file and i need to write on its (let's say) 5th line. how should I workout the correct offset for it?

I know its not simply (5) the line number. so I'm guessing its the total length of existing data up to the beginning of 5th line. If so is there any specific length for each line of file, or (most likely) it's variable based on the line's content? and if its variable how should I find it out?

Any advise will be appreciated.

Ali
  • 2,993
  • 3
  • 19
  • 42
  • 2
    seek() works with a "byte" offset, not line numbers. Unless you're working with a known fixed length for lines (which lets you do a bit of maths to work out what the offset should be) then you need to read each line at a time to get to the offset you want.... computers can't magically guess when line lengths might be purely arbitrary – Mark Baker Jul 01 '15 at 11:00
  • Many thanks, @MarkBaker – Ali Jul 01 '15 at 11:05

1 Answers1

0

Here is an example based on gnarf's answer here

<?php

$targetFile = './sample.txt';
$tempFile = './sample.txt.tmp';

$source = fopen($targetFile , 'r');
$target = fopen($tempFile, 'w');

$whichLine = 5;
$whatToReplaceWith = 'Here is the new value for the line ' . $whichLine;

$lineCounter = 0;
while (!feof($source)) {

    if (++$lineCounter == $whichLine) {
        $lineToAddToTempFile = $whatToReplaceWith;
    } else {
        $lineToAddToTempFile = fgets($source);
    }

    fwrite($target, $lineToAddToTempFile);
}

unlink($targetFile);
rename($tempFile, $targetFile);

which will change (replace) sample.txt with the following content:

line one
line two
line three
line four
line five

to

line one
line two
Here is the new value for the line 3line three
line four
line five
Community
  • 1
  • 1