Search code examples
c++fstreamifstream

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.


Solution

  • 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.