相关文章推荐
刚毅的啤酒  ·  vue ...·  4 月前    · 
聪明的领结  ·  java - Netty ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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.

I can confirm this. Have file of 368 bytes, the vector size is only 312. GCC version is gcc (Debian 4.4.5-8) 4.4.5. – Some programmer dude Nov 10, 2011 at 6:57

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

is >> std::noskipws;
                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, 2011 at 8:13
                @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, 2011 at 10:18

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>());
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.