从文件读取最后一行 [英] Read last line from file
问题描述
问题是这个动作会经常通过AJAX请求调用该日志的文件大小超过5-6MB,这对服务器来说并不好。所以我想我必须阅读最后一行,但不能读取整个文件并通过它,或将其加载到RAM中,因为这只会加载到我的盒子死亡。
这个操作是否有任何优化,使其运行顺利,不会伤害服务器或杀死Apache?
我的其他选项是 exec('tail -n 1 / path / to / log')
但是听起来不太好。
稍后编辑:我不想将文件放在RAM中,因为它可能会变得巨大。 这应该工作: 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 Later edit: I DO NOT want to put the file in RAM because it might get huge. This should work:
这篇关于从文件读取最后一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
$ 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;
exec('tail -n 1 /path/to/log')
but it doesn't sound so good.fopen()
is not an option.$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;