How to read a growing text file in C++?

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

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

if it is really necessary to close and reopen the same file for this purpose.

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

Leave a Comment