Read a file backwards line by line using fseek

后端 未结 9 2031
温柔的废话
温柔的废话 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:11

    Reading the entire file into an array and reversing is fine unless the file is enormous.

    You could perform a buffered read of your file from back to front with something like this:

    • establish a buffer_size B - this should be longer than the longest anticipated line otherwise you'll need some logic for growing the buffer size when lines are too long
    • set offset = file length - buffer_size
    • while the offset>=0
      • read buffer_size bytes from offset
      • read a line - it will be incomplete as we'll have jumped into the middle of a line, so we want to ensure the next buffer we read ends with it. Set offset = offset - buffer_size + line length
      • discard that line, read all following lines into an array and reverse them
      • process this array to do whatever you wanted to do

提交回复
热议问题