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 :
std::fstream chfile;
chfile.open(filename.c_str(), std::fstream::binary | std::fstream::out);
if (chfile.good())
{
chfile << (unsigned char)0x02 << (unsigned char)0x46 << (unsigned char)0x8A << (unsigned char)0xCE;
// other input
chfile.close();
}
Reading magic number :
std::fstream chfile;
chfile.open(filename.c_str(), std::fstream::binary | std::fstream::in);
if (chfile.good())
{
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);
chfile.close();
}
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.operator>>recognizes12as whitespace, and skips it, searching for the next valid character.Try using an unformatted input operation (like
chfile.read()orchfile.get()) instead.