0

I'm trying to use a stream in order to read from a vector of existing data.

// 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
}

However when I call seekg it throws an exception (or reports error normally if not using exceptions). Why is this? 10 is within the 100 chars of input data.

Code needs to work with both C++11 and before compilers.

Live example: http://ideone.com/PfpW0o

Neil Kirk
  • 21,327
  • 9
  • 53
  • 91

1 Answers1

0

std::basic_streambuf::seekpos by default returns pos_type(off_type(-1)) according to http://en.cppreference.com/w/cpp/io/basic_streambuf/pubseekpos

istream::seekg() in order threats that as error condition, so you need to override that function in your class vectorwrapbuf and return actual position.

Slava
  • 43,454
  • 1
  • 47
  • 90