5

I have the following code which I have been using on a 188 byte file:

std::ifstream is("filename", std::ios::binary);

std::vector<uint8_t> buffer;
std::istream_iterator<uint8_t> i_input(is);
std::copy(i_input, std::istream_iterator<uint8_t>(),
          std::back_inserter(buffer));

std::cout << buffer.size();

However it is only reading 186 bytes of the 188 bytes.

I have confirmed the file size in a hexeditor as well as with ls -al.

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
Rory Hart
  • 1,813
  • 1
  • 19
  • 19

2 Answers2

13

I don't know why, but by default that seems to skip whitespace. You need to disable that with noskipws:

is >> std::noskipws;
Timo
  • 5,125
  • 3
  • 23
  • 29
  • That was it for me. Though I find it weird that the stream should skip whitespace when opened in binary mode. – Some programmer dude Nov 10 '11 at 08:13
  • 2
    @JoachimPileborg: That has nothing to do with binary modes. You're using *formatted extraction*, which does all sorts of mangling and skipping. Arguably, formatted-extracting into a `char` must be the worst way to read in a raw file! – Kerrek SB Nov 10 '11 at 10:18
  • @KerrekSB You're right. Must have been to early for me to think properly I guess. – Some programmer dude Nov 10 '11 at 10:20
  • Oooh! That makes sense, frustrating that it wasn't documented anywhere I was reading. – Rory Hart Nov 10 '11 at 22:32
9

What are the last two bytes? Also, you don't really need a istream_iterator for reading binary data like this. That's overkill and probably slower than using streambuf.

See this example from wilhelmtell's great answer:

#include<iterator>
// ...

std::ifstream testFile("testfile", std::ios::in | std::ios::binary);
std::vector<char> fileContents((std::istreambuf_iterator<char>(testFile)),
                               std::istreambuf_iterator<char>());
Community
  • 1
  • 1
Assaf Lavie
  • 73,079
  • 34
  • 148
  • 203