About the PHP method fseek (), what exactly is shifted (position)?

It may be my English, but the explanation in PHP Manual (cited below) does not provide a clear answer to my question.

To go to the position to the end of the file, you need to pass a negative value at the offset and set the value for SEEK_END.

I have a file, and I need to write on it (let them say) the 5th line. How do I set the correct offset?

I know it is not just (5) the line number. so I assume the total length of the existing data to the beginning of the 5th row. If so, is there any specific length for each line of the file, or (most likely) is it a variable based on the contents of the line? and if its a variable, how do I recognize it?

Any recommendations would be appreciated.

+5
source share
1 answer

Here is an example based on gnarf 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 
0
source

All Articles