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

Viewed 10302

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

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

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.

Thank you.

4 Answers

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

    }
}
Related