Possible Duplicate:
Reading from text file until EOF repeats last line
c++ EOF running one too many times?
I am writing a simple c++ code to read and write a binary file but I found that the ifstream will read the record twice. I don't know how this happens but I try to compile the code with mingw32 in windows and linux, the same case
ofstream outfile;
int data[5];
outfile.open("abc.out", ios::out | ios::trunc | ios::binary);
data[0] = data[1] = 1;
data[2] = data[3] = 2;
data[4] = -1;
cout << "ORIGINAL DATA:" << data[0] << " " << data[1] << " " << data[2] << " " << data[3] << " " << data[4] << endl << endl;
outfile.write((char *)&data[0], 5*sizeof(int));
outfile.close();
ifstream infile;
infile.open("abc.out", ios::in | ios::binary);
data[0] = data[1] = data[2] = data[3] = data[4] = 0;
while (!infile.eof())
{
infile.read((char *)&data[0], 5*sizeof(int));
cout << data[0] << " " << data[1] << " " << data[2] << " " << data[3] << " " << data[4] << endl;
}
Here is the output
ORIGINAL DATA:1 1 2 2 -1
1 1 2 2 -1
1 1 2 2 -1
Answer
Don't ever use .eof()
or .good()
as loop condition. It almost always produces buggy code (as it does in this case).
The idiomatic pattern for reading data is C++ is this:
while (infile.read((char *)&data[0], 5*sizeof(int)))
{
cout << data[0] << " " << data[1] << " " << data[2] << " "
<< data[3] << " " << data[4] << endl;
}
No comments:
Post a Comment