簡體   English   中英

將istream與自定義streambuf一起使用時seekg不起作用

[英]seekg doesn't work when using istream with custom streambuf

我試圖使用流,以便從現有數據的向量中讀取。

// http://stackoverflow.com/questions/8815164/c-wrapping-vectorchar-with-istream
template<typename CharT, typename TraitsT = std::char_traits<CharT> >
class vectorwrapbuf : public std::basic_streambuf<CharT, TraitsT>
{
public:
    vectorwrapbuf(std::vector<CharT> &vec)
    {
        this->setg(&vec[0], &vec[0], &vec[0] + vec.size());
    }
};

int main()
{
    vector<char> data(100, 1);
    vectorwrapbuf<char> databuf(data);
    std::istream file(&databuf);
    file.exceptions(std::istream::failbit | std::istream::badbit);
    file.seekg(10); // throws
}

但是,當我調用seekg它將引發異常(如果不使用異常,則通常會報告錯誤)。 為什么是這樣? 10在輸入數據的100個字符內。

代碼需要與C ++ 11以及之前的編譯器一起使用。

實時示例: http//ideone.com/PfpW0o

默認情況下, std::basic_streambuf::seekpos根據http://en.cppreference.com/w/cpp/io/basic_streambuf/pubseekpos返回pos_type(off_type(-1))

istream::seekg()順序將其威脅為錯誤情況,因此您需要在類vectorwrapbuf覆蓋該函數並返回實際位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM