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

siv3szwd  于 2023-01-28  发布在  其他
关注(0)|答案(4)|浏览(148)

我正在尝试读取一个正在增长的文件(类似于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,我试图存储文件的当前结束位置,以便当我重新打开它时,我可以直接进入那里并读取添加的内容。
我想知道我的代码中有什么错误,以及是否真的有必要为此关闭并重新打开同一个文件。
谢谢你。

zqry0prt

zqry0prt1#

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

while (getline(ifs, log))
{
    cout << log << endl;
    p = ifs.tellg();
}

此外,由于tellg()返回-1p声明为size_t,因此p的值被设置为4294967295。这意味着seekg()被设置为超出文件结尾。将p的类型更改为std::streamoff,并确认对seekg()的调用是否成功:

if (ifs.seekg(p))
{
    while (getline(ifs, log))
    {
        cout << log << endl;
        p = ifs.tellg();
    }
}

如果确实有必要为此关闭并重新打开同一文件。
不,这不是必须的,但是您需要从流中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;
}
nwo49xxi

nwo49xxi2#

既然这些答案都不管用,我想出了一个确实管用的...

#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();

    }
}
qyuhtwio

qyuhtwio3#

这个方法对我很有效:

#include <string>
#include <chrono>
#include <thread>
#include <fstream>
#include <iostream>

int main(int, char* argv[])
{
    // open file passed in on command line (at end of file)
    std::ifstream ifs(argv[1], std::ios::ate);

    if(!ifs.is_open())
    {
        std::cerr << "ERROR: opening log file: " << argv[1] << '\n';
        return 1;
    }

    // remember file position
    std::ios::streampos gpos = ifs.tellg();

    std::string line;
    bool done = false;

    while(!done)
    {
        // try to read line
        if(!std::getline(ifs, line) || ifs.eof())
        {
            // if we fail, clear stream, return to beginning of line
            ifs.clear();
            ifs.seekg(gpos);

            // and wait to try again
            std::this_thread::sleep_for(std::chrono::milliseconds(100));
            continue;
        }

        // remember the position of the next line in case
        // the next read fails
        gpos = ifs.tellg();

        // process line here
        std::cout << "line: " << line << std::endl;
    }
}
6rvt4ljy

6rvt4ljy4#

这个代码对我有效:

struct timespec pause;
pause.tv_sec  = 1;
pause.tv_nsec = 0;

std::ifstream ifs("test.log");
std::streamoff p;

if(ifs.is_open())
{
    std::string line;

    while(true)
    {
        if(ifs.seekg(p))
        {
            while(std::getline(ifs, line))
            {
                std::cout << line << std::endl;
                p = ifs.tellg();
            }
        }

        ifs.clear();

        nanosleep(&pause, NULL);
    }
}

相关问题