I'm writing four ints (a=1, b=2, c=3, d=4) to a binary file in C++ with fstream, but when I try to read them back, they do not match.
First of all, the written binary is 4 bytes long. Shouldn't it be 16 bytes (4 ints x 4 bytes/int)? When I read, I get the weird result 1234 2 3 4 if I do not zero-initialize the variables in the read function, or 1234 0 0 0 if I do.
Also, how is the result being modified by the zero-initialization? I know not initializating can lead to nasty results, but how exactly are the variables in read() getting those values that match the ones in write()?
#include <fstream>
#include <iostream>
void write()
{
std::ofstream output( "test.bin", std::fstream::binary | std::fstream::out);
int a=1, b=2, c=3, d=4;
output << a << b << c << d;
output.close();
}
void read()
{
std::ifstream input( "test.bin", std::fstream::binary | std::fstream::in);
int a, b, c, d;
// int a=0, b=0, c=0, d=0;
input >> a >> b >> c >> d;
input.close();
std::cout << a << " " << b << " " << c << " " << d << " " << std::endl;
}
int main()
{
write();
read(); // Shows 1234 2 3 4 or 1234 0 0 0
}
operator<<(..., int)is a FormattedOutputFunction. It's formatting the integers as strings with no separation between them. Concatenated strings of digits look indistinguishable from a single integer (1234) when you read it back. You can trivially confirm this by looking at your own file. Usehexdumpor similar to be safe if you expect it to be an un-printable binary file.a. The values ofb,c,dare basically random, that's why the zero init changes them..read/.writefunctions.0is assigned in case extraction failed. In any case there is nothing "random"0since the values are1,2,3. I assume they just happen to fall into the same memory as before, i.e. random.