繁体   English   中英

如何实现自定义std :: streambuf的seekoff()?

[英]How to implement custom std::streambuf's seekoff()?

基于例如这个问题和答案,我有以下实现

struct membuf : std::streambuf
{
  membuf(char* begin, char* end)
  {
    this->setg(begin, begin, end);
  }

protected:
  virtual pos_type seekoff(off_type off,
                           std::ios_base::seekdir dir,
                           std::ios_base::openmode which = std::ios_base::in)
  {
    std::istream::pos_type ret;
    if(dir == std::ios_base::cur)
    {
      this->gbump(off);
    }
    // something is missing here...
  }
};

我想以下列方式在我的方法中使用它:

  char buffer[] = { 0x01, 0x0a };
  membuf sbuf(buffer, buffer + sizeof(buffer));
  std::istream in(&sbuf);

然后调用比如tellg()in ,并得到正确的结果。

到目前为止它几乎是完美的 - 它不会在流的末尾停止。

我应该如何升级它以使其正常工作?

我的主要动机是模仿std::ifstream行为,但在测试中将二进制char[]输入它们(而不是依赖于二进制文件)。

对于将搜索方向设置为std::ios_base::begstd::ios_base::end情况,接受的答案不起作用。 要支持这些情况,请通过以下方式扩展实施:

pos_type seekoff(off_type off,
                 std::ios_base::seekdir dir,
                 std::ios_base::openmode which = std::ios_base::in) {
  if (dir == std::ios_base::cur)
    gbump(off);
  else if (dir == std::ios_base::end)
    setg(eback(), egptr() + off, egptr());
  else if (dir == std::ios_base::beg)
    setg(eback(), eback() + off, egptr());
  return gptr() - eback();
}

看来我错过了当前位置的回报。 因此,最终实施的seekoff如下:

  pos_type seekoff(off_type off,
                   std::ios_base::seekdir dir,
                   std::ios_base::openmode which = std::ios_base::in)
  {
    if (dir == std::ios_base::cur) gbump(off);

    return gptr() - eback();
  }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM