Rub*_*rgh 1 c++ buffer iostream
将内存流上的答案seekoff与上的答案结合在一起,我实现了内存中的缓冲区,如下所示:
struct membuf : std::streambuf {
membuf(char const* base, size_t size) {
char* p(const_cast<char*>(base));
this->setg(p, p, p + size);
}
};
struct imemstream : virtual membuf, std::istream {
imemstream(char const* base, size_t size) :
membuf(base, size),
std::istream(static_cast<std::streambuf*>(this)) {
}
std::iostream::pos_type seekoff(std::iostream::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();
}
};
Run Code Online (Sandbox Code Playgroud)
然而,在第一aswer的意见作为解释,我们仍然需要得到seekg/ seekpos工作。那么如何在seekpos这里正确实现呢?
PS:这个问题的方向相同,但是给出了更具体的答案。
由于尚未得到答复,因此我在此处发布了建议的实现。
pos_type seekpos(pos_type sp, std::ios_base::openmode which) override {
return seekoff(sp - pos_type(off_type(0)), std::ios_base::beg, which);
}
Run Code Online (Sandbox Code Playgroud)
另外,在seekoff其他方向上,实施不适用于我。考虑通过以下方式对其进行修改:
pos_type seekoff(off_type off,
std::ios_base::seekdir dir,
std::ios_base::openmode which = std::ios_base::in) override {
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();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
699 次 |
| 最近记录: |