How to read a fixed number of bytes from a c++ std::istream

三世轮回 提交于 2019-12-24 08:10:55

问题


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

回答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".



来源:https://stackoverflow.com/questions/37780054/how-to-read-a-fixed-number-of-bytes-from-a-c-stdistream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!