My first question is, why is it customary to use unsigned chars for writing to files in binary mode? In all of the examples I have seen, any other numerical value is casted to unsigned char before writing to the binary file.
My second question is, what’s so bad about using stream operators to write to binary files? I’ve heard that read() and write() operators are best used for writing to binary files, but I don’t really understand why that’s the case. Using stream operators to write to binary files works fine for me IF I first cast the value to unsigned char.
float num = 500.5;
ostream file("file.txt", ios::binary);
file << num // results in gibberish when I try to read the file later
file << (unsigned char)num // no problems reading the file with stream operators
Thanks in advance.
charsare the smallest type in C/C++ (by definition,sizeof( char ) == 1). Its the usual way to see objects as a sequence of bytes.unsignedis used to avoid signed arithmethic to get in the way, and because it best represents binary contents (a value between 0 and 255).To operate on binary files, streams provide the
readandwritefunctions. The insertion and extraction functionality is formatted. It’s working for you just by chance, for instance if you output an integer with << then it will actually output the textual representation of the integer value and not its binary representation. In your provided example, you cast a float to an unsigned char before outputing, actually casting the real value to a small integer. What do you get when you try to read the float back from the file?