Read last line from file

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

    If you know the upper bound of line length you could do something like this.

    $maxLength = 1024;
    $fp = fopen('somefile.txt', 'r');
    fseek($fp, -$maxLength , SEEK_END); 
    $fewLines = explode("\n", fgets($fp, $maxLength));
    $lastLine = $fewLines[count($fewLines) - 1];
    

    In response to the edit: fopen just acquires a handle to the file (i.e. make sure it exists, process has permission, lets os know a process is using the file, etc...). In this example only 1024 characters from the file will be read into memory.

提交回复
热议问题