[英]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::beg
或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();
}
看來我錯過了當前位置的回報。 因此,最終實施的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.