Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

istream

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?

like image 467
Hhut Avatar asked Apr 09 '26 11:04

Hhut


2 Answers

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.

like image 134
James Kanze Avatar answered Apr 12 '26 02:04

James Kanze


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.

like image 36
Ulrich Eckhardt Avatar answered Apr 12 '26 02:04

Ulrich Eckhardt



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!