istream::tellg() returns -1 when used with my custom streambuf class?
Asked Answered
S

1

7

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?

Stere answered 20/7, 2011 at 14:37 Comment(3)
Do you know that seekg() isn't rewinding? Have you proven that tellg() works properly?Declaim
Yes, after calling seekg(0), getline() doesn't read my first line. The tellg() function definitely doesn't work, as it always returns -1, (even when I just started reading from my buffer). I believe Bo's answer is the way to go here...Stere
E@dSanville: OK; I clarified your question accordingly.Declaim
J
7

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).

Jailhouse answered 20/7, 2011 at 14:53 Comment(3)
Thank you very much! I will implement those right away. I'm curious though, how does istream::tellg() use those functions? Does it call streambuf::seekoff(0, ios_base::cur) and get the return value?Stere
In effect, yes. It actually calls pubseekoff, which then calls seekoff, but that's an interface design detail. :-)Jailhouse
I am trying to do this... implement seekoff & seekpos on a custom membuf class, except there's a problem in my code: seekoff is not being called consistently by tellg and seekpos is not called at all. Any suggestions or working examples?Reparation

© 2022 - 2024 — McMap. All rights reserved.