Search code examples
c++stlistream-iterator

Is there any way to use istreambuf_iterator to read a specific length?


I'm writing my files like this:

std::ofstream os; // declared somewhere earlier
std::vector<char> vec; // declared somewhere earlier

std::ostreambuf_iterator<char> oi(os);
std::copy(vec.begin(), vec.end(), oi);

So naturaly I was wondering if there was a similar way to read let's say 5 bytes using the std::istream_iterator or std::istreambuf_iterator, however since they don't support the operator+ I can't seem to figure out how to accomplish this.

For example I imagined a soludion close to this:

std::istream_iterator<char> ii(file);
std::copy(ii, ii + 5, vec.begin());

Is there any way to do this in C++14?

PS: I want a solution using STL, so using boost is not an option.


Solution

  • You can use std::copy_n instead of std::copy.

    std::copy_n(ii, 5, vec.begin());
    

    However, this is a bit unsafe since it will keep trying to read even if the stream is exhausted. If that is of concern to you, then you will either have to use a lower level construct like a basic for loop, or a library with more advanced range handling capabilities, like Eric Niebler's excellent range library.