从文件读取最后一行 [英] Read last line from file

查看:147
本文介绍了从文件读取最后一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在碰到一个问题。我有一个Linux框上的日志,其中写入了几个正在运行的进程的输出。这个文件有时会变得非常大,我需要从该文件中读取最后一行。



问题是这个动作会经常通过AJAX请求调用该日志的文件大小超过5-6MB,这对服务器来说并不好。所以我想我必须阅读最后一行,但不能读取整个文件并通过它,或将其加载到RAM中,因为这只会加载到我的盒子死亡。



这个操作是否有任何优化,使其运行顺利,不会伤害服务器或杀死Apache?



我的其他选项是 exec('tail -n 1 / path / to / log')但是听起来不太好。



稍后编辑:我不想将文件放在RAM中,因为它可能会变得巨大。


解决方案

这应该工作:

  $ line =''; 

$ f = fopen('data.txt','r');
$ cursor = -1;

fseek($ f,$ cursor,SEEK_END);
$ char = fgetc($ f);

/ **
*修剪文件的尾随换行符
* /
while($ char ===\\\
|| $ char = ==\r){
fseek($ f,$ cursor--,SEEK_END);
$ char = fgetc($ f);
}

/ **
*直到开始文件或第一个换行符char
* /
读取($ char!== false& ;& $ char!==\\\
& && $ char!==\r){
/ **
*预加新的char
* /
$ line = $ char。 $线;
fseek($ f,$ cursor--,SEEK_END);
$ char = fgetc($ f);
}

echo $ line;


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 need to read the last line from that file.

The problem is this action will be called via an AJAX request pretty often and when the file size of that log gets over 5-6MB it's rather not good for the server. So I'm thinking I have to read the last line but not to read the whole file and pass through it or load it in RAM because that would just load to death my box.

Is there any optimization for this operation so that it run smooth and not harm the server or kill Apache?

Other option that I have is to exec('tail -n 1 /path/to/log') but it doesn't sound so good.

Later edit: I DO NOT want to put the file in RAM because it might get huge. fopen() is not an option.

解决方案

This should work:

$line = '';

$f = fopen('data.txt', '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);
}

echo $line;

这篇关于从文件读取最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆