How can I read the entire stream into std :: vector?

I read the answer here which shows how to read an entire stream into a std :: string with the following (two) liners:

std::istreambuf_iterator<char> eos;    
std::string s(std::istreambuf_iterator<char>(stream), eos);

      

To do something similar to reading a binary stream in std::vector

, why can't I just replace char

with uint8_t

and std::string

with std::vector

?

auto stream = std::ifstream(path, std::ios::in | std::ios::binary);    
auto eos = std::istreambuf_iterator<uint8_t>();
auto buffer = std::vector<uint8_t>(std::istreambuf_iterator<uint8_t>(stream), eos);

      

The above compiler error (VC2013):

1> d: \ non-svn \ C ++ \ library \ i \ file \ filereader.cpp (62): error C2440: ': cannot convert from' std :: basic_ifstream> 'to' std :: istreambuf_iterator> '1 >
with 1> [1> _Elem = uint8_t 1>] 1>
Constructor cannot use source type or constructor overload resolution was ambiguous

+3


source to share


2 answers


There's just a type mismatch. ifstream

is just a typedef:

typedef basic_ifstream<char> ifstream;

      

So, if you want to use a different base type, just tell it:

std::basic_ifstream<uint8_t> stream(path, std::ios::in | std::ios::binary);    
auto eos = std::istreambuf_iterator<uint8_t>();
auto buffer = std::vector<uint8_t>(std::istreambuf_iterator<uint8_t>(stream), eos);

      



This works for me.

Or, since Dietmar says it might be a little sketchy, you can do something like:

auto stream = std::ifstream(...);
std::vector<uint8_t> data;

std::for_each(std::istreambuf_iterator<char>(stream),
              std::istreambuf_iterator<char>(),
              [&data](const char c){
                  data.push_back(c);
              });

      

+9


source


ifstream

- flow char

, not uint8_t

. You will need basic_ifstream<uint8_t>

or istreambuf_iterator<char>

for the respective types.



The former may not work without some work, since the library is only required to support threads char

and wchar_t

; so you probably want istreambuf_iterator<char>

.

+5


source







All Articles