我有以下基于例如的实现这个问题和答案 https://stackoverflow.com/questions/6763646/istreamtellg-returns-1-when-used-with-my-custom-streambuf-class
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::beg
or std::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();
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)