skipws flag set when opening an input file stream

2019-02-26 04:38发布

问题:

I know the extraction operator should not be used on an input stream opened in binary mode, but the member function read should be used instead.

std::ifstream ifs("file.bin", std::ios::in | std::ios::binary);
char c;
ifs >> c; // Should not be used
ifs.read(&c, 1); // OK

But it can be done anyway. So my question is what is the rationale for not unsetting the skipws flag on input file streams when opened in binary mode?

回答1:

"Binary" mode, as controlled by std::ios_base::binary is only for switching off the translation of newlines between the standard C++ \n character and the system specific newline sequence as stored in files.

It's completely independent of whether you are parsing a file that contains meaningful separating whitespace or some completely different byte format so there's no reason to tie the two orthogonal pieces of functionality together.

(The C++ standard doesn't say much about what binary mode means, there is more detail in the C standard which talks about the potential differences between text streams and binary streams. Binary streams must read back byte for byte as they were written on any given system whereas text stream need only do so given a number of restrictions centring around not having extra spaces before a newline and not having any control characters other than newlines and tabs. A system need not make any distinction at all between binary and text streams.)