我想知道如何在 C/C++ 中实现类似于 tail -f
的程序,一个监视和处理添加到日志文件的新行的程序?
最佳答案
您可以使用 fseek() 清除流上的 eof 条件。本质上,读到文件末尾,休眠一会儿,fseek()(不改变你的位置)清除eof,再次读到文件末尾。清洗、漂洗、重复。 man fseek(3) 了解详情。
这是它在 perl 中的样子。 perl 的 seek() 本质上是 fseek(3) 的包装器,所以逻辑是一样的:
wembley 0 /home/jj33/swap >#> cat p
my $f = shift;
open(I, "<$f") || die "Couldn't open $f: $!\n";
while (1) {
seek(I, 0, 1);
while (defined(my $l = <I>)) {
print "Got: $l";
}
print "Hit EOF, sleeping\n";
sleep(10);
}
wembley 0 /home/jj33/swap >#> cat tfile
This is
some
text
in
a file
wembley 0 /home/jj33/swap >#> perl p tfile
Got: This is
Got: some
Got: text
Got: in
Got: a file
Hit EOF, sleeping
然后,在另一个 session 中:
wembley 0 /home/jj33/swap > echo "another line of text" >> tfile
回到原来的程序输出:
Hit EOF, sleeping
Got: another line of text
Hit EOF, sleeping
关于c++ - 实现日志观察器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22379/