I'm working on ubuntu 10.04 and a gcc. I have a binary file with my own magic number. When I read the file, the magic number is not the same. The streams seams to be correct.
Writing magic number :
chfile.open(filename.c_str(), std::fstream::binary | std::fstream::out);
chfile << (unsigned char)0x02 << (unsigned char)0x46 << (unsigned char)0x8A << (unsigned char)0xCE;
// other input
Reading magic number :
chfile.open(filename.c_str(), std::fstream::binary | std::fstream::in);
unsigned char a,b,c,d;
chfile >> a;
chfile >> b;
chfile >> c;
chfile >> d;
printlnn("header must : " << (int)0x02 << ' ' << (int)0x46 << ' ' << (int)0x8A << ' ' << (int)0xCE); // macro for debugging output
printlnn("header read : " << (int)a << ' ' << (int)b << ' ' << (int)c << ' ' << (int)d);
When I use 02 46 8A CE as magic number it's alright (as the output says):
header must : 2 70 138 206
header read : 2 70 138 206
but when I use EA 50 0C C5 then the output is :
header must : 234 80 12 197
header read : 234 80 197 1
and the last 1 is a legit value for the next input. So why differ they and how do I fix this ?
In the second case,
operator>> is skipping over the character value 12.
12 as whitespace, and skips it, searching for the next valid character.
Try using an unformatted input operation (like
You shouldn't use
>> with binary files, they are used for formatted reading and writing.
In particular, they do special handling of whitespace such as 0xC (i.e. formfeed), which makes them unsuitable for binary I/O.