Question

The following code only prints the file once:

#include <iostream>
#include <fstream>
using namespace std;

int main(int argc, const char *argv[])
{
    ifstream infile;
    infile.open("in", ios::binary);
    char c;

    while (infile.get(c))
    {
        cout << c;
    }

    infile.seekg(0, ios::beg);
    infile.clear();

    while (infile.get(c))
    {
            cout << c;
    }
    infile.close(); 
    return 0;
}

I assume it has something to do with the eof flag after running through the file, but I don't know how to fix that.

Cheers.

Was it helpful?

Solution

There are several problems with your code:

First, you don't check that infile.get() succeeds before using its results, ever. And you are using infile.good() to control one loop, and infile.eof() to control another: infile.eof() isn't useful until you know that the input has failed, and infile.good() is never really useful. Just use while ( infile.get( c ) ) for both loops.

Second, as you say, you never reset the "error" that caused you to finish the first loop. Once you've encountered the end of file (and infile.get( c ) has failed), you need to call infile.clear() before doing anything else.

Finally, of course, you fail to check whether you successfully opened the file, and whether the seekg succeeded. And you generally don't have to close an input file; it will be closed automatically when it goes out of scope. (On the other hand, you should either close or flush std::cout, and verify that it is still OK afterwards. Returning 0 when you've failed to write all of the data is a serious error in my book.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top