Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I read fstream's binary data with operator>>?

If I do something like the following:

ifstream file;
file.open("somefile", ios::binary);

unsigned int data;

file >> data;

My stream will always set the failbit and the data will remain uninitialized. However, if I read a char or unsigned char instead, the stream is fine. perror() is telling me "result too large".

The only thing I saw on Google was a suggestion saying that operator>> shouldn't be used for binary data (prefer read()), but I find the operator to be cleaner and easier to use -- and it doesn't require casting everything.

Can someone explain this issue?

like image 294
Galf Avatar asked Nov 11 '10 06:11

Galf


People also ask

How do you read binary data?

The best way to read a binary number is to start with the right-most digit and work your way left. The power of that first location is zero, meaning the value for that digit, if it's not a zero, is two to the power of zero, or one. In this case, since the digit is a zero, the value for this place would be zero.

Which function is used to read binary data from a file?

Use the fread Function to Read Binary File in C fread is part of the C standard library input/output facilities, and it can be utilized to read binary data from regular files.


1 Answers

The iostream extraction operator (>>) attempts to interpret numerical strings separated by whitespace, not binary data. There are many different ways to encode an unsigned integer in binary form (e.g. a 32-bit 2's complement representation in little-endian byte order). That's why you must use the read/write functions to operate on such binary buffers.

However, nothing prevents you from implementing your own class for serializing binary data in whatever form you wish using the insertion and extraction operators. Such a class would likely use the read function of an ifstream object internally. Alternatively, the boost serialization library may already hold exactly what you want.

like image 126
Judge Maygarden Avatar answered Sep 23 '22 00:09

Judge Maygarden