1

How to read a fixed number of bytes from a std::istream without doing any extraction? For example, I have a variable sz of type size_t and I would like to read sizeof(size_t) bytes from the istream.

void foo(std::istream& is) {
  if(is.rdbuf()->in_avail() < sizeof(size_t)) return;
  // how to read to sz from istream is without extraction (advancing pointers)
  size_t sz;
}
user207421
  • 305,947
  • 44
  • 307
  • 483
Jes
  • 2,614
  • 4
  • 25
  • 45
  • 1
    what do you mean when you say "without doing any extraction"? what about the read method? is it applied to your "without doing any extraction"? – AnatolyS Jun 12 '16 at 23:25
  • 'Fix-byte data' is meaningless. Please don't invent your own terminology. – user207421 Jun 13 '16 at 00:46

1 Answers1

1

You can only peek the next character without extracting.

As such, you should change your strategy: instead of trying to avoid extraction, extract the characters that you need, and then restore the state of the stream. That is possible if the stream supports seeking:

  • use tellg to get the current position
  • extract the bytes
  • use seekg to jump to the earlier position

Otherwise, you may need to implement a buffer of your own to do whatever you're trying to achieve by "reading without extracting".

eerorika
  • 232,697
  • 12
  • 197
  • 326