Read a file backwards line by line using fseek

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

    This code read file backwards. This code ignore modifications on reading, example apache access.log new lines on procressing.

    $f = fopen('FILE', 'r');
    
    fseek($f, 0, SEEK_END);
    
    $pos = ftell($f);
    $pos--;
    
    while ($pos > 0) {
        $chr = fgetc($f);
        $pos --;
    
        fseek($f, $pos);
    
        if ($chr == PHP_EOL) {
            YOUR_OWN_FUNCTION($rivi);
            $rivi = NULL;
            continue;
        }
    
        $rivi = $chr.$rivi;
    }
    
    fclose($f);
    

提交回复
热议问题