Hhut
Hhut

Reputation: 1198

connect std::istream directly to C-Array/unsigned char *

I'm currently dealing with a custom buffer class which in its inside carries around its data in a classic C-Array (unsigned char[]).

To get a more comfortable read/write access to that buffer I was looking for a way to construct an std::istream object which is directly connected to the POD content... aka the C-Array memory. The goal is to using all the std::stream formatters and the actual data "lorem ipsum" should be directly written to the buffer. So something like this:

std::istream QuirkyBuffer::getIStream() { return std::istream(this->ptr, this->size); }

QuirkyBuffer d;
auto is = d.getIStream();
"lorem ipsum" >> is;

Is it possible to do that?

Upvotes: 3

Views: 807

Answers (2)

Ulrich Eckhardt
Ulrich Eckhardt

Reputation: 17415

The istream is not the problem, the problem is writing a streambuffer, because e.g. ifstream is just a class derived from istream and containing a streambuffer and some glue code. Now, in order to write a streambuffer, you need to override the private virtual input functions. I think underflow() and uflow() are even enough, but using these keywords you should be able to find the required info yourself.

BTW: Streams are not copyable, unless that changed in C++11, so returning by value is a no-go.

Upvotes: 1

James Kanze
James Kanze

Reputation: 153929

You can use std::ostrstream for this. It's deprecated, but given its usefulness, I can't imagine it going away anytime soon.

Otherwise, it's very simple to write your own omemstream.

Upvotes: 2

Related Questions