I'm facing a problem reading a boolean from a binary file in C++ (visual studio 2015/windows). Before trying to read the boolean the istream is good but after reading the failbit is set while the stream is not eof and the badbit is also not set.
Some documentation on the failbit states: "Returns true in the same cases as bad(), but also in the case that a format error happens, like when an alphabetical character is extracted when we are trying to read an integer number."
Basically I don't understand how reading a boolean from a binary stream can ever fail if the stream is good before and not eof after. My assumption is that since there is only one bit read as a boolean, there is no formatting. Perhaps there are other conditions in which the failbit is set?
void Parser::binary2Record(std::istream& in) {
bool is_next_booking;
in >> current_record_;
in >> is_next_booking;
Segment segment;
while (!is_next_booking && in) {
in >> segment;
current_record_.addSegment(segment);
std::cout << "State of io before reading boolean " << (in.good() ? "Good" : "Not good") << std::endl;
in >> is_next_booking;
std::cout << "State of io good after reading boolean " << (in.good() ? "Good" : "Not good") << std::endl;
std::cout << "State of io fail after reading boolean " << (in.fail() ? "fail" : "Not fail") << std::endl;
std::cout << "State of io bad after reading boolean " << (in.bad() ? "Bad" : "Not Bad") << std::endl;
std::cout << "State of io eof after reading boolean " << (in.eof() ? "Eof" : "Not eof") << std::endl;
}
}
Output:
State of io before reading boolean Good
State of io good after reading boolean Not good
State of io fail after reading boolean fail
State of io bad after reading boolean Not Bad
State of io eof after reading boolean Not eof
That is where your problem lies.
stream >> bool_var
does formatted input (it is looking for the characters "true" or "false"). If you want to do unformatted input, you have to usestream.read()
orstream.get()
.The only thing that uses
ios_base::openmode::binary
does, is change how end of line characters are handled.