问题
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