Read a file backwards line by line using fseek

后端 未结 9 2032
温柔的废话
温柔的废话 2020-11-27 07:33

How do I read a file backwards line by line using fseek?

code can be helpful. must be cross platform and pure php.

many thanks in advance

regards

9条回答
  •  独厮守ぢ
    2020-11-27 08:13

    The question is asking using fseek, so can only assume that performance is an issue and file() is not the solution. Here is a simple approach using fseek:

    My file.txt

    #file.txt
    Line 1
    Line 2
    Line 3
    Line 4
    Line 5
    

    And the code:

    Output:

    array(5) {
       [0]=>
       string(6) "Line 5"
       [1]=>
       string(6) "Line 4"
       [2]=>
       string(6) "Line 3"
       [3]=>
       string(6) "Line 2"
       [4]=>
       string(6) "Line 1"
    }
    

    You don't have to append to the $lines array like I am, you can print the output straight away if that is the purpose of your script. Also it is easy to introduce a counter if you want to limit the number of lines.

    $linesToShow = 3;
    $counter = 0;
    while ($counter <= $linesToShow && -1 !== fseek($fp, $pos, SEEK_END)) {
       // Rest of code from example. After $lines[] = $currentLine; add:
       $counter++;
    }
    

提交回复
热议问题