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

How to read a growing text file in C++?(如何在 C++ 中读取不断增长的文本文件?)
本文介绍了如何在 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.

谢谢.

推荐答案

由于这些答案都不起作用,我想出了一个可行的方法...

Since none of these answers worked, i came up with one that does work...

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

    }
}

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

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Prevent class inheritance in C++(防止 C++ 中的类继承)
Why should I declare a virtual destructor for an abstract class in C++?(为什么要在 C++ 中为抽象类声明虚拟析构函数?)
Why is Default constructor called in virtual inheritance?(为什么在虚拟继承中调用默认构造函数?)
C++ cast to derived class(C++ 转换为派生类)
C++ virtual function return type(C++虚函数返回类型)
Is there any real risk to deriving from the C++ STL containers?(从 C++ STL 容器派生是否有任何真正的风险?)