如何在C++中阅读不断增长的文本文件?

Pie*_*tro 10 c++ logging fstream stl seekg

我试图从正在增长的文件(类似于什么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);
}
Run Code Online (Sandbox Code Playgroud)

如果没有//*1和//*2的行,日志文件会被正确读取到最后,但是如果添加新行,则不会发生任何事情.

使用seekg和tellg我试图存储文件的当前结束位置,这样当我重新打开它时,我可以去那里并阅读已添加的内容.

我想知道我的代码有什么问题,如果真的有必要为此目的关闭并重新打开同一个文件.

谢谢.

hmj*_*mjd 15

循环不正确,因为eof()遇到tellg()返回时,并且在需要调用之后-1没有eof()立即检查getline().将循环更改为:

while (getline(ifs, log))
{
    cout << log << endl;
    p = ifs.tellg();
}
Run Code Online (Sandbox Code Playgroud)

另外,由于p被声明为size_ttellg()返回-1的值p被设定为4294967295.这意味着将seekg()其设置为超出文件末尾.变更的类型p,以std::streamoff确认调用seekg()成功:

if (ifs.seekg(p))
{
    while (getline(ifs, log))
    {
        cout << log << endl;
        p = ifs.tellg();
    }
}
Run Code Online (Sandbox Code Playgroud)

如果确实有必要为此目的关闭并重新打开同一个文件.

不,这不是必要的,但你需要来自流clear()eof状态.以下是已发布代码的更正版本的替代方法:

#include <iostream>
#include <string>
#include <fstream>

int main()
{
    std::ifstream ifs("test.log");

    if (ifs.is_open())
    {
        std::string line;
        while (true)
        {
            while (std::getline(ifs, line)) std::cout << line << "\n";
            if (!ifs.eof()) break; // Ensure end of read was EOF.
            ifs.clear();

            // You may want a sleep in here to avoid
            // being a CPU hog.
        }
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)


小智 3

由于这些答案都不起作用,我想出了一个有效的答案......

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{
    string   log, logFile("test.txt");
    std::streamoff   p = 0;
    ifstream ifs(logFile.c_str());

    while(true)
    {

        ifs.seekg(p);  //*1
        while (getline(ifs, log))
        {
            cout << log << endl;
            if(ifs.tellg() == -1) p = p + log.size();
            else p = ifs.tellg();
        }
        ifs.clear();

    }
}
Run Code Online (Sandbox Code Playgroud)