Read a file backwards line by line using fseek

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

    To completely reverse a file:

    $fl = fopen("\some_file.txt", "r");
    for($x_pos = 0, $output = ''; fseek($fl, $x_pos, SEEK_END) !== -1; $x_pos--) {
        $output .= fgetc($fl);
        }
    fclose($fl);
    print_r($output);
    
    

    Of course, you wanted line-by-line reversal...

    
    $fl = fopen("\some_file.txt", "r");
    for($x_pos = 0, $ln = 0, $output = array(); fseek($fl, $x_pos, SEEK_END) !== -1; $x_pos--) {
        $char = fgetc($fl);
        if ($char === "\n") {
            // analyse completed line $output[$ln] if need be
            $ln++;
            continue;
            }
        $output[$ln] = $char . ((array_key_exists($ln, $output)) ? $output[$ln] : '');
        }
    fclose($fl);
    print_r($output);
    
    

    Really though, Jonathan Kuhn has the best answer IMHO above. The only cases you'd not use his answer that I know of is if file or like functions are disabled via php.ini, yet the admin forgot about fseek, or when opening a huge file just get the last few lines of contents would magically save memory this way.

    Note: Error handling not included. And, PHP_EOL didn't cooperate, so I used "\n" to denote end of line instead. So, above may not work in all cases.

提交回复
热议问题