c++ - How to read entire stream into a std::vector? -


I read how to read an entire stream in the std :: string with the following one (two) liners: / P>

  std :: istreambuf_iterator & lt; Char & gt; EOS; Std :: string s (std :: istreambuf_iterator & lt; char & gt; (section), EOS); To do something to read a binary stream in   

a std :: vector , why can not I just replace char std :: vector with uint8_t and std :: string ?

  auto stream = std :: ifstream (path, std :: IOS :: in | std :: IOS :: binary); Auto eos = std :: istreambuf_iterator & lt; Uint8_t & gt; (); Auto buffer = std :: vector & lt; Uint8_t & gt; (Std :: istreambuf_iterator & lt; uint8_t & gt; (section), eos);  

produces the above compiler error (VC 2013):

1> D: \ non-svn \ c ++ \ library \ i \ File \ filereader. CPP (62): Error C2440: '': 'std :: basic_ifstream>' with 'std :: istreambuf_iterator>' 1> with 1> [1> _Elem = uint8_t 1>] 1>
No constructor source type Can not take, or the constructor overload resolution was unclear

There is just one type mismatch < Code> ifstream is just a typedef:

  typedef basic_ifstream & lt; Char & gt; Ifstream;  

So if you want to use a different underlying type, you have to tell:

  std :: basic_ifstream & lt; Uint8_t & gt; Stream (path, std :: IOS :: in | std :: IOS :: binary); Auto eos = std :: istreambuf_iterator & lt; Uint8_t & gt; (); Auto buffer = std :: vector & lt; Uint8_t & gt; (Std :: istreambuf_iterator & lt; uint8_t & gt; (section), eos);  

This works for me.

Or, because the dieter says that it can be a little lid, you can do something like this:

  auto stream = std :: ifstream (... ); Std :: vector & lt; Uint8_t & gt; Information; Std :: for_each (std :: istreambuf_iterator & lt; char> (stream), std :: istreambuf_iterator & lt; char & gt; (), [& amp; data] (const char c) {data.push_back ( C);});  

Comments