c++ - ifstream operator >> uint16_t sets failbit -


i'm trying ready binary-file set of variables using c++ std::ifstream class.

the following example works:

std::ifstream infile; infile.open("example.bin"); uint8_t temp8; uint16_t temp16; infile >> temp8; infile >> temp8; 

but if replace last 2 lines 1 line

infile >> temp16; 

nothing read , infile.fail() returns true.

can explain, why can't read 16 bit variable?

the operator>> overload reading uint16_t istreams formatted input function, meaning not read binary data, reads string , if necessary converts number (e.g. using strtoul or similar).

as explained @ http://en.cppreference.com/w/cpp/io/basic_istream

the class template basic_istream provides support high level input operations on character streams. supported operations include formatted input (e.g. integer values or whitespace-separated characters , characters strings) , unformatted input (e.g. raw characters , character arrays).

infile >> temp16 tries read sequence of (usually) ascii digits, first non-digit character, converts sequence of digits number, , if fits in uint16_t stores in temp16. if reading binary file istream not going find sequence of ascii digits, reading fails.

you need use unformatted input function read 16 bits directly file without trying interpret string number, like:

infile.read(reinterpret_cast<char*>(&temp16), 2); 

Comments

Popular posts from this blog

angularjs - ADAL JS Angular- WebAPI add a new role claim to the token -

php - CakePHP HttpSockets send array of paramms -

node.js - Using Node without global install -