File Read Line by Line

I am trying to read from a text file that is continuously getting more and more data. Since the rate that it is being updated with data is slower than the rate that C++ is running I am having problems with the program. I am trying to put the file reader inside of a infinite loop (which should continuously read a line even when it reached the end of the file).

Here is my code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main ()
{
    string STRING;
    ifstream infile;
    infile.open ("test.txt");
    int a=0;
    string previousLine="";
    while(a<1) // To get you all the lines.
    {
        getline(infile,STRING); // Saves the line in STRING.
        if (STRING != previousLine)
        {
            previousLine=STRING;
            cout<<STRING<<endl; // Prints our STRING.
        }

    }
    infile.close();
    system ("pause");
}


It works until it reaches the end of the file. Does anyone have any sugestions on how I can achieve a file reader in C++ that reads at the speed that data is being added to the text file?

Thanks!
How do you know you're getting EOF? You ceretainly aren't testing for it?!?
Are you compiling a release build for your testing?

You could eliminate a little bit of string copying by using your (suitably renamed) strings for odd and even line numbers respectively. The logic should be easy enough.

You could also get your strings to preallocate (reserve method).

You also need to check eof(), bad(), etc. in your loop. But allow for the possibilty that you overtake the file briefly, if it slows down for a short while.
Last edited on
once you're finished reading the file, store the offset and then keep checking if the filesize is bigger, then start reading from that offset
Thanks Kiana, that solved the problem!
Maybe my code would help the others who needs the easy example. ^_^
It can be run under Qt4.
==========
#include <QtCore/QCoreApplication>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);

string sLine = "";
ifstream infile;

infile.open("temp.txt");

while (!infile.eof())
{
getline(infile, sLine);
cout << sLine << endl;
}

infile.close();
cout << "Read file completed!!" << endl;

return a.exec();
}
Topic archived. No new replies allowed.