0

As this link [https://stackoverflow.com/a/8815308/1068715] said:

I use setg(vec.data(), vec.data(), vec.data() + vec.size()); to initialize a streambuf. After that, read() on istream working properly, but tellg() always return -1, and seekg() always failed.

anyone can help?

Raven
  • 345
  • 2
  • 10

2 Answers2

1

seekg and tellg ask the streambuf via pubseekoff and pubseekpos to actually perform the work. The default implementation of these functions simply fail.

You need to implement seekoff and seekpos in your streambuf.

T.C.
  • 133,968
  • 17
  • 288
  • 421
  • You mean override `seekoff` and `seekpos`, right? I check stringstream's implementation, it's too complicate. Is any other solution to wrap vector into stream? thanks – Raven Nov 08 '18 at 00:52
  • `stringbuf`'s implementation is hard because you can mix read and write. It's not hard for a read-only streambuf. – T.C. Nov 08 '18 at 00:59
  • ok, I tried to implement as stringstream does, seems working fine for now – Raven Nov 08 '18 at 01:40
1

Thanks for asking this; I came across the same problem after referencing the same link.

I'd just like to add that if you're having a seekg() problem and concerned about implementing this, I would vouch for the Boost option:

boost::iostreams::basic_array_source<char> isrc(vec.data(), vec.size());
boost::iostreams::stream< typeof(isrc) > istr(isrc);

because you get this seek functionality for free straight out the box instead of having to write an implementation yourself.

ZeroDefect
  • 663
  • 1
  • 8
  • 27