Read last line from file

后端 未结 12 1725
南方客
南方客 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条回答
  •  -上瘾入骨i
    2020-12-01 10:00

    this the code of Ionuț G. Stan

    i modified your code a little and made it a function for reuseability

    function read_last_line ($file_path){
    
    
    
    $line = '';
    
    $f = fopen($file_path, '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);
    }
    
    return $line;
    }
    

    echo read_last_line('log.txt');

    you will get that last line

提交回复
热议问题