我正在尝试读取一个正在增长的文件(类似于tail -F
所做的事情),但是我的代码肯定有一些问题:
string log, logFile("test.log");
size_t p = 0;
while(true)
{
ifstream ifs(logFile.c_str());
ifs.seekg(p); //*1
while(ifs.eof() == false)
{
getline(ifs, log);
cout << log << endl;
p = ifs.tellg(); //*2
}
nanosleep(&pause, NULL);
}
如果没有行//* 1和//* 2,日志文件将正确读取到其结尾,但如果添加新行,则不会发生任何情况。
使用seekg和tellg,我试图存储文件的当前结束位置,以便当我重新打开它时,我可以直接进入那里并读取添加的内容。
我想知道我的代码中有什么错误,以及是否真的有必要为此关闭并重新打开同一个文件。
谢谢你。
4条答案
按热度按时间zqry0prt1#
循环不正确,因为当遇到
eof()
时,tellg()
返回-1
,并且在调用getline()
之后没有立即检查eof()
,而需要检查getline()
。将循环更改为:此外,由于
tellg()
返回-1
时p
声明为size_t
,因此p
的值被设置为4294967295
。这意味着seekg()
被设置为超出文件结尾。将p
的类型更改为std::streamoff
,并确认对seekg()
的调用是否成功:如果确实有必要为此关闭并重新打开同一文件。
不,这不是必须的,但是您需要从流中
clear()
eof
状态。以下是发布的代码的更正版本的替代方法:nwo49xxi2#
既然这些答案都不管用,我想出了一个确实管用的...
qyuhtwio3#
这个方法对我很有效:
6rvt4ljy4#
这个代码对我有效: