streambuf :: getting the data back from a custom stream
For a particular application of mine - I need a simulation of byte
array output stream.
* write data onto a stream
* getback the contiguous content as an array later for network
transport.
My code looks as follows.
#include <iostream>
#include <streambuf>
#include <locale>
#include <cstdio>
using namespace std;
class outbuf : public std::streambuf
{
public:
virtual ~outbuf()
{
sync();
}
char * getData() const
{
std::cout << "First " << std::hex << (void *)pbase() ;
std::cout << "Current " << std::hex << (void *)pptr() ;
return pbase();
}
streamsize getSize() const
{
return pbase() - pptr();
}
};
class myostream : public std::basic_ostream<char>
{
public:
myostream() :
basic_ostream<char>(new outbuf)
{
}
~myostream()
{
delete rdbuf();
}
};
int main()
{
myostream out;
out << "31 hexadecimal: " << std::hex << 31 << "\n";
st = out.rdbuf();
buf = dynamic_cast<outbuf *>(st);
if (!buf)
{
cerr << "error: dynamic_Cast failed";
return EXIT_FAILURE;
}
//TODO: At this point - I need to get the pointer to the beginning
of the buffer and the size of the same.
buf->getData();
cerr << "Size: " << buf->getSize() << endl;
return 0;
}
I had gone about creating a rudimentary derived class implementation
of streambuf and an output stream.
After writing data to the output stream I need to get the number of
bytes written and the pointer to the beginning of the stream. How do I
go about doing the same ??
The above example does not seem to work btw.
Thanks for the help.