开发者

Efficient way to replace the last line from a file?

Is there an efficient way to replace the last line from a file?

I need this for log files, to have this kind of line:

21:00:00 - Info - Count: 3

Be replaced with this:

21:00:35 - Info - Count: 4

And so on.. So it looks cool in a tail -f

The problem is that log files can get really big, and I 开发者_StackOverflow社区don't want them being loaded into the memory everytime I want to replace the last line.

Anyway, if loading the whole file was the only way, how would you go about it, having in mind that there are other scripts appending data to the same file, simultaneously? I guess I have to lock it or something. I never used that because I just use file_put_contents with the FILE_APPEND option.


If you want an efficient way, then read in a block of content from the end, then truncate on the last found \n. That's not pretty, but works:

$fn = "LICENSE";
$size = filesize($fn);
$block = 4096;
$trunc = max($size - $block, 0);

$f = fopen($fn, "c+");
if (flock($f, LOCK_EX)) {
   fseek($f, $trunc);
   $bin = rtrim(fread($f, $block), "\n");
   if ($r = strrpos($bin, "\n")) {
      ftruncate($f, $trunc + $r + 1);
   }
}
fclose($f);   // clears LOCK_EX
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜