I have a char* and the data length that I'm receiving from a library, and I need to pass the data to a function that takes an istream.
I know I can create a stringstream but that will copy all the data. And also, the data will surely have 0s since it's a zip file, and creating a stringstream will take the data until the first 0 I think.
Is there any way to create an istream from a char* and it's size without copying all the data?
A non deprecated solution using Boost:
or even simpler:
The only (simple) portable way includes making the copy:
In fact, this is likely to copy the data twice, once to create the
string
and once to create theistringstream
. (Maybe C++11 can avoid one of the copies via a move constructor; I am not sure.)However, if you are lucky, your C++ implementation will let you do this:
Under GNU C++ (and, I believe, some other implementations), this will create the stringstream without copying the data. But this is "implementation-defined" behavior according to the spec. (See also this question.)
By including the
len
parameter, you ensure that both of these will have no problem with null characters.The only portable way to do what you want is to implement your own subclass of
stringbuf
and use it to initialize the stringstream. Not for the faint of heart.Have you tried std::istrstream? http://stdcxx.apache.org/doc/stdlibref/istrstream.html
Technically, I think that it is deprecated, but still part of the standard.
I needed a solution that supports
tellg
andseekg
and didn't require boost.char_array_buffer
from A beginner's guide to writing a custom stream buffer (std::streambuf) gave a got starting point.byte_array_buffer.h:
byte_array_buffer.cpp:
Try the Boost.Iostreams array source and sink classes.
http://www.boost.org/doc/libs/1_47_0/libs/iostreams/doc/index.html
Here's a non-deprecated method found on the web, has you derive your own
std::streambuf
class, but easy and seems to work:Which outputs: