Why doesn't this program read (or write?) Correctly from the .bin file? (C ++)
I created this program:
#include <iostream>
#include <fstream>
using namespace std;
int main () {
fstream file;
file.open("test.bin", ios::in | ios::out | ios::binary);
if(!file.is_open())
{
return -1;
}
int n = 5;
int x;
file.write(reinterpret_cast<char*>(&n), sizeof(n));
file.read(reinterpret_cast<char*>(&x), sizeof(x));
std::cout<<x;
file.close();
std::cin.ignore();
return 0;
}
which should write the integer "n" to the .bin file "test.bin", then read the data from "test.bin" into the integer "x", and then display the "x" on the screen.
When I run the program, it displays not 5 but -842150451. Why is this happening and how can I fix it?
0
user98188
a source
to share
4 answers