问题
i'm trying to ready a binary-file into a set of variables using the 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 i replace the last two lines with one line
inFile >> temp16;
nothing is read and inFile.fail()
returns true
.
Can anyone explain, why I can't read into a 16 bit variable?
回答1:
The operator>>
overload for reading uint16_t
from istreams is a formatted input function, meaning does not read binary data, it reads a string and if necessary converts it to a number (e.g. using strtoul
or similar).
As explained at http://en.cppreference.com/w/cpp/io/basic_istream
The class template
basic_istream
provides support for high level input operations on character streams. The supported operations include formatted input (e.g. integer values or whitespace-separated characters and characters strings) and unformatted input (e.g. raw characters and character arrays).
inFile >> temp16
tries to read a sequence of (usually) ASCII digits, up to the first non-digit character, then converts that sequence of digits to a number, and if it fits in uint16_t
stores it in temp16
. If you are reading from a binary file then the istream is probably not going to find a sequence of ASCII digits, so reading fails.
You need to use an unformatted input function to read 16 bits directly from the file without trying to interpret a string as a number, like:
inFile.read(reinterpret_cast<char*>(&temp16), 2);
回答2:
The extraction of an integer from a stream with >>
expects to find ascii numeric digits. If it doesn't find them, it sets the fail status.
If your uint16_t
data is not by pure coincidence composed by two bytes, which the first appear to be between 0x30 and 0x39, it's doomed to fail. ANd if it would succed, it wouldn't be the values that you expect.
For binary data use:
inFile.read (&temp16, sizeof(temp16));
and of course, open the file with ios::binary
mode.
来源:https://stackoverflow.com/questions/30550887/ifstream-operator-uint16-t-sets-failbit