问题
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?
回答1:
The functions tellg and seekg depends on protected virtual functions seekoff
and seekpos
, that you would have to implement in your membuf
class.
The defaults in basic_streambuf
just returns pos_type(off_type(-1))
for all calls (which might be equal to -1 for many implementaions).
来源:https://stackoverflow.com/questions/6763646/istreamtellg-returns-1-when-used-with-my-custom-streambuf-class