如何读取C ++中不断增长的文本文件? [英] How to read a growing text file in C++?

查看:97
本文介绍了如何读取C ++中不断增长的文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图读取一个正在增长的文件(类似于 tail -F ),但是我的代码必须有一些问题:

I am trying to read from a file which is growing (something similar to what tail -F does), but there must be some problems with my code:

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,日志文件

Without the lines //*1 and //*2, the log file is correctly read up to its end, but if new lines are added nothing happens.

使用seekg和tellg我试图存储文件的当前结束位置,因此,当我重新打开它时,我可以去那里,看看已经添加了什么。

With seekg and tellg I am trying to store the current end position of the file, so that when I reopen it I can go strait there and read what has been added.

我想知道我的代码是什么,如果真的有必要。

I would like to know what is wrong in my code, and if it is really necessary to close and reopen the same file for this purpose.

谢谢。

推荐答案

遇到 eof()时,循环不正确 tellg() 返回 -1 ,并且没有检查<$ c $紧跟在调用 getline()之后的c> eof()将循环变更为:

The loop is incorrect as when eof() is encountered tellg() returns -1 and there is no check for eof() immediately after the call to getline() which there needs to be. Change loop to:

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

此外, p tellg() return -1 时,会被声明为 size_t c> p 的值设置为 4294967295 。这意味着 seekg()被设置为超出文件的末尾。将 p 的类型更改为 std :: streamoff ,并确认调用 seekg 已成功:

Additionally, as p is declared as a size_t when tellg() return -1 the value of p was being set to4294967295. This meant the seekg() was being set to beyond the end of the file. Change the type of p to std::streamoff and confirm the call to seekg() was successful:

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







不是,它是没有必要,但您需要从流中 clear() eof 状态。以下是已发布代码的更正版本的替代方案:

No, it is not necessary but you need to clear() the eof state from the stream. The following is an alternative to a corrected version of the posted code:

#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;
}

这篇关于如何读取C ++中不断增长的文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆