gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:19:17 26 4
gpt4 key购买 nike

我有以下实现基于例如this question and answer

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() on 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();
}

关于c++ - 如何实现自定义 std::streambuf 的 seekoff()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35066207/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com