问题
I came across Reading the binary file into the vector of unsigned chars and tested the code discussed in the question.
The code of interest is below:
typedef unsigned char BYTE;
std::ifstream file(filename, std::ios::binary);
file.unsetf(std::ios::skipws);
std::vector<BYTE> vec;
vec.insert(vec.begin(),
std::istream_iterator<BYTE>(file),
std::istream_iterator<BYTE>());
According to Benjamin Lindley's answer at Why std::istream_iterator ignores newline characters?, istream::operator>>(char)
skips white spaces. But the type above is unsigned char
, and the file was opened with std::binary
.
Why did the code require an explicit call to file.unsetf(std::ios::skipws)
(or alternately, file >> std::noskipws)
?
回答1:
The basic algorithm for >> of a string is:
1) skip whitespace
2) read and extract until next whitespace
If you use noskipws
, then the first step is skipped
.
After the first read, you are positionned on a whitespace, so the next (and all following) reads will stop immediatly, extracting nothing.
来源:https://stackoverflow.com/questions/21803615/need-for-noskipws-on-stream-with-t-unsigned-char-in-binary-mode