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.
There are several problems with your code:
First, you don’t check that
infile.get()succeeds before usingits results, ever. And you are using
infile.good()to controlone 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 usewhilefor both loops.( infile.get( c ) )
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 callinfile.clear()before doing anything else.Finally, of course, you fail to check whether you successfully
opened the file, and whether the
seekgsucceeded. And yougenerally 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 thatit is still OK afterwards. Returning
0when you’ve failed towrite all of the data is a serious error in my book.)