Read last line from file

后端 未结 12 1724
南方客
南方客 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 09:50

    Use fseek. You seek to the last position and seek it backward (use ftell to tell the current position) until you find a "\n".

    
    $fp = fopen(".....");
    fseek($fp, -1, SEEK_END); 
    $pos = ftell($fp);
    $LastLine = "";
    // Loop backword util "\n" is found.
    while((($C = fgetc($fp)) != "\n") && ($pos > 0)) {
        $LastLine = $C.$LastLine;
        fseek($fp, $pos--);
    }
    

    NOTE: I've not tested. You may need some adjustment.

    UPDATE: Thanks Syntax Error for pointing out about empty file.

    :-D

    UPDATE2: Fixxed another Syntax Error, missing semicolon at $LastLine = ""

提交回复
热议问题