Question

I tried to build a stream buffer for reading and writing char* using boost::iostreams:

class MemBuf : public std::streambuf
{
public:
  MemBuf(char* s, std::size_t n)
  {
      setg(s, s, (char*)s+ n);
  }
};

reading works fine:

char myreadBuff[100];
myreadBuff[0] = 'a';
MemBuf mb (myreadBuff, 100);
istream istr (&mb);
cout << istr; 

but writing does not work:

char mywriteBuff[100];
MemBuf mb(mywriteBuff, 100);
ostream ostr($mb);

ostr << "hello world";

cout << mywriteBuff;

What is missing?

Thx

Was it helpful?

Solution

setg sets the pointers for the read area; it has no effect on writing.

The simplest solution is to use two different streambuf, MemBufIn and MemBufOut: the first calls setg, and the second setp. If you want a bidirectional stream, or to support seeking, it gets more complicated.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top