Hello! My problem can be described the following way:
I have some data which开发者_StackOverflow社区 actually is an array and could be represented as char* data
with some size
I also have some legacy code (function) that takes some abstract std::istream
object as a param and uses that stream to retrieve data to operate.
So, my question is the following - what would be the easy way to map my data
to some std::istream
object so that I can pass it to my function? I thought about creating a std::stringstream
object from my data
, but that means copying and (as I assume) isn't the best solution.
Any ideas how this could be done so that my std::istream
operates on the data
directly?
Thank you.
If you're looking at actually creating your own stream, I'd look at the Boost.Iostreams library. It makes it easy to create your own stream objects.
Definitely not the easiest way but just in case someone wanted to understand how std streams work inside, this seems to be a very nice introduction about how you can roll your own:
http://www.mr-edd.co.uk/blog/beginners_guide_streambuf
Use string stream:
#include <sstream>
int main()
{
char[] data = "PLOP PLOP PLOP";
int size = 13; // PS I know this is not the same as strlen(data);
std::stringstream stream(std::string(data, size));
// use stream as an istream;
}
If you want to be real effecient you can muck with the stream buffer directly. I have not tried this and do not have a compiler to test with, but the folowing should work:
#include <sstream>
int main()
{
char[] data = "PLOP PLOP PLOP";
int size = 13; // PS I know this is not the same as strlen(data);
std::stringstream stream;
stream.rdbuf()->pubsetbuf(data, size);
// use stream as an istream;
}
精彩评论