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?

Lightness Races in Orbit
  • 358,771
  • 68
  • 593
  • 989
EdSanville
  • 103
  • 7

1 Answers1

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

Patryk
  • 18,244
  • 37
  • 110
  • 212
Bo Persson
  • 86,087
  • 31
  • 138
  • 198
  • 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? – EdSanville Jul 20 '11 at 15:02
  • In effect, yes. It actually calls pubseekoff, which then calls seekoff, but that's an interface design detail. :-) – Bo Persson Jul 20 '11 at 15:06
  • 2
    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? – Brian McFarland Jun 30 '15 at 20:16