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

五迷三道 提交于 2019-12-07 05:46:35

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!