简体   繁体   中英

Missing data when reading binary file in C++

vector<byte> h;
ifstream fin(file.c_str(), ios::binary);
if(!fin)
    return false;
byte b;
while(fin >> b)
    h.push_back(b);

The length of h is 4021, while the raw file length is 4096 bytes. But the code below gives a string of 4096 bytes. Why?

ostringstream sout;
sout << fin.rdbuf();
string s = sout.str();

UPDATES:

@user2079303 solved my problem, but any other way to perform the reading task. It's too easy to get it wrong.

When reading input stream char by char (your bytes are chars, right?), standard streams ignore whitespace by default. You can use std::noskipws to stop ignoring them.

fin >> std::noskipws >> b;

Note: ios::binary has no effect on this behaviour even though one might expect so. It only disables translating line-endings as far as I know.

If you don't want to worry about processing, you can use functions that fulfill UnformattedInputFunction . cppreference has a nice example on how to read a binary file with istream::read .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM