Read file into std::vector<std::byte>

I'm trying to read a file in binary format into a std::vector<std::byte>

You are using std::istream_iterator, which reads from an std::istream using operator>>, which performs a formatted read instead of a binary read by default. Use std::istream::read() to read binary data.

If you want to use std::istring_iterator to read bytes, you would need to define a custom operator>> that calls std::istream::read() or std::stream::get(). But this would be inefficient since it would read 1 byte at a time. It is better to call read() directly to read blocks of multiple bytes at a time. For instance, query the file size, preallocate the std::vector to that size, and then read() from the std::ifstream directly into the std::vector for that size.

Update: I just noticed that you are using std::istreambuf_iterator instead of std::istream_iterator. std::istreambuf_iterator does not use operator>>, so it would be better suited for reading bytes. However, it still reads 1 byte at a time, so what I said about using std::istream::read() to read multiple bytes at a time still applies.


you should be able to do it like this:

  std::basic_ifstream<std::byte> fStream{fName, std::ios::binary};

  std::vector<std::byte> file_content{ std::istreambuf_iterator<std::byte>(fStream), {} };

Tags:

C++

C++17