I am working on a test on C++ where one program writes an object in a file, and another program reading the contents of the file.
The write segment:
DClass cc;
ofstream ofs;
ofs.open("data.dat", ios::binary);
cc.enroll = 11;
cc.name = "tom the cat";
ofs.write((char *)&cc, sizeof(cc));
The read segment:
DClass cc;
ifstream ifs;
ifs.open("data.dat", ios::binary);
while (!ifs.eof())
{
ifs.read((char *)&cc, sizeof(cc));
cout << cc.enroll << " " << cc.name << endl;
}
The structure of DClass:
struct ConClass
{
int enroll;
string name;
};
When running the read program, the output is the data in the file, but twice,
11 tom the cat
11 tom the cat
It seems that the program has no errors but the while loop in the read program does not reach the eof after reading the data, so it print the data in the cc
which is not overwritten in the second iteration.
What can I do to make sure the program runs properly?
I am compiling this in mingw on windows, and do not see such problem in Borland C++.