I am studying binary file of C++ nowadays. I made a example code for it, but it does not work well.
#include <iostream>
#include <fstream>
using namespace std;
int main() {
ofstream writeFile;
ifstream readFile;
int temp = 1;
writeFile.open("file.dat", ios::binary);
for (int i = 5; i <= 10 ; i++) // range 5 to 10
writeFile.write((char*)(&i), sizeof(i));
writeFile.close();
readFile.open("file.dat", ios::binary);
readFile.seekg(0);
while (!readFile.eof()) {
readFile.read((char*)(&temp), sizeof(temp));
cout << "temp: " << temp << endl;
readFile >> ws;
}
readFile.close();
system("pause");
return 0;
}
Here is the result:
temp: 5
temp: 6
temp: 7
temp: 8
temp: 167772160
temp: 167772160
When I change the range not to include 9 (for example, 5 to 8), it works well. Also, When I make the same code with double type, it works well. So I think the integer 9 is problem. Can you tell me why?