Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read vector<char> as stream

Tags:

c++

stl

I have a CONST vector lying around, but need a function to read from it. The problem is, the function expects an istream.

What's the most efficient way to pass the data inside the vector to this function?

I tried this approach to prevent copying the stream, but it doesn't work because my vector is const and pubsetbuf expects a non-const char *.

istringstream is;
const vector<char>& data = GETDATA();
is.rdbuf()->pubsetbuf(&data[0], data.size());

As the stream is read-only, I could cast the pointer. Is that safe? Or any better ways?

like image 276
Neil Kirk Avatar asked Oct 27 '25 07:10

Neil Kirk


1 Answers

Consider using Boost.Iostreams:

#include <boost/iostreams/device/array.hpp>
#include <boost/iostreams/stream.hpp>

using namespace boost::iostreams;
stream<array_source> bs(data.data(), data.size());
std::istream &is = bs;
like image 77
ecatmur Avatar answered Oct 29 '25 22:10

ecatmur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!