Read last line from file

后端 未结 12 1747
南方客
南方客 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:39

    Here is a compilation of the answers here wrapped into a function which can specify how many lines should be returned.

    function getLastLines($path, $totalLines) {
      $lines = array();
    
      $fp = fopen($path, 'r');
      fseek($fp, -1, SEEK_END);
      $pos = ftell($fp);
      $lastLine = "";
    
      // Loop backword until we have our lines or we reach the start
      while($pos > 0 && count($lines) < $totalLines) {
    
        $C = fgetc($fp);
        if($C == "\n") {
          // skip empty lines
          if(trim($lastLine) != "") {
            $lines[] = $lastLine;
          }
          $lastLine = '';
        } else {
          $lastLine = $C.$lastLine;
        }
        fseek($fp, $pos--);
      }
    
      $lines = array_reverse($lines);
    
      return $lines;
    }
    

提交回复
热议问题