thorsan
thorsan

Reputation: 1064

Using std::istream_iterator to read binary data from file stops prematuraly

I am trying to read binary data from file using the following code:

std::ifstream fp;
fp.open("C:\\my_binary_data.dat", std::ios::binary);
std::istream_iterator<byte> start(fp), end;
std::vector<byte> tof(start, end);
fp.close();

The file has 401 bytes, but the tof vector is only 380 elements long, i.e. it stops reading before the end. The end is set to nullptr(?), thus the iterator reads until it reads a zero byte? The 380th byte is 109. What is the stop condition here? And how can I be sure it reads the whole file?

Using

fp.seekg (0, fp.end);
std::streamoff length = fp.tellg();
fp.seekg (1, fp.beg);

gives length=401

Upvotes: 1

Views: 460

Answers (1)

istream_iterator is an avatar of operator >>; it uses that operator to read from the stream. That is almost never what you want for reading binary data, because >> is a formatted input function. You could probably coerce it to do what you want by using manipulators such as noskipws on the stream, but it would still effectively remain a use of the wrong tool for the job.

If you want an iterator-based access to binary data in a stream, you might be better off using an istreambuf_iterator (which is guaranteed to work character by character) instead.

Upvotes: 4

Related Questions