Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using std::ifstream, std::istream_iterator and std::copy is not reading entire file

Tags:

c++

stl

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.

like image 242
Rory Hart Avatar asked Nov 10 '11 06:11

Rory Hart


2 Answers

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

is >> std::noskipws;
like image 195
Timo Avatar answered Oct 26 '22 18:10

Timo


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>());
like image 24
Assaf Lavie Avatar answered Oct 26 '22 18:10

Assaf Lavie