Read last line from file

后端 未结 12 1729
南方客
南方客 2020-12-01 09:13

I\'ve been bumping into a problem. I have a log on a Linux box in which is written the output from several running processes. This file can get really big sometimes and I ne

12条回答
  •  独厮守ぢ
    2020-12-01 10:02

    This should work:

    $line = '';
    
    $f = fopen('data.txt', 'r');
    $cursor = -1;
    
    fseek($f, $cursor, SEEK_END);
    $char = fgetc($f);
    
    /**
     * Trim trailing newline chars of the file
     */
    while ($char === "\n" || $char === "\r") {
        fseek($f, $cursor--, SEEK_END);
        $char = fgetc($f);
    }
    
    /**
     * Read until the start of file or first newline char
     */
    while ($char !== false && $char !== "\n" && $char !== "\r") {
        /**
         * Prepend the new char
         */
        $line = $char . $line;
        fseek($f, $cursor--, SEEK_END);
        $char = fgetc($f);
    }
    
    echo $line;
    

提交回复
热议问题