I must be missing something simple here, but I am trying to write and read a binary file in C++.
ofstream file3("C:\\data2.txt", ios::out | ios::binary);
for (int i = 0; i < 100; i++) {
file3.write((char*)(&i), sizeof(int));
}
ifstream file4("C:\\data2.txt", ios::in | ios::binary);
int temp;
while (!file4.eof()) {
file4.read((char*)(&temp), sizeof(int));
cout << temp << endl;
}
The file looks like it is getting created properly when viewed with a hex editor. However, as I go to read the file it reads 1 random junk value and quits vs. listing out all the numbers.
Update
I made a slight update based on the comments and all seems good now. On Windows the close made a difference and I did fix the loop condition.
ofstream file3("C:\\data2.txt", ios::out | ios::binary);
for (int i = 0; i < 100; i++) {
file3.write((char*)(&i), sizeof(int));
}
file3.close();
ifstream file4("C:\\data2.txt", ios::in | ios::binary);
//cout << file4.eof();
int temp;
while (!file4.read((char*)(&temp), sizeof(int)).eof()) {
cout << temp << endl;
}