I’m trying to create an istream that reads directly from a raw memory buffer.
I found a nice way to do this in another post on here:
class membuf : public basic_streambuf<char>
{
public:
membuf(char* p, size_t n) {
setg(p, p, p + n);
}
};
Then I create my istream using this membuf:
membuf mb(dataPointer, dataLength);
istream reader(&mb);
I then read using getline() and >> operators, and everything is wonderful. However, I can’t seem to use seekg() to rewind back to the beginning of my buffer, and istream::tellg() always returns -1.
Do I need to write some more code to get these to work, or is this doomed to failure?
The functions tellg and seekg depends on protected virtual functions
seekoffandseekpos, that you would have to implement in yourmembufclass.The defaults in
basic_streambufjust returnspos_type(off_type(-1))for all calls (which might be equal to -1 for many implementaions).