Vlad has provided an improved version of Code #1, I'll provide a better Code #2:
basic_filebuf<uint8_t> ifb;
ifb.open("file.dat", ios_base::in | ios_base::binary);
vector<uint8_t> v;
v.resize(ifb.pubseekoff(0, ios_base::end));
ifb.pubseekpos(0);
ifb.sgetn(&v[0], v.size());
The fact is that an ifstream
is not intended for processing unformatted data, even when ios_base::binary
is used to open it. That flag is somewhat misnamed -- it disables newline translations, but it doesn't cause insertion and extraction operations to use binary encodings.
This version should be quite a lot faster, not only because there's less copying when the vector is preallocated, but because filebuf xsgetn
can be expected to transfer large blocks, whereas iterators access single elements. Even if there is a buffer used to do large block transfers at the I/O level, the virtual calls per-character imposed by the iterators will kill performance.