问题
I did a simple test with C++ code and using the helper tool pv
(pipe viewer).
The code is:
#include <iostream>
#include <array>
int main() {
std::array<char,4096> buffer;
while( true ) {
std::cin.readsome(buffer.data(),4096);
}
}
I execute with:
pv /dev/urandom | ./a.out
Through pv
, I notice that readsome
never reads anything. What am I missing?
回答1:
Please see cppreference, especially under "Notes".
The behavior of this function is highly implementation-specific. For example, when used with
std::ifstream
, some library implementations fill the underlyingfilebuf
with data as soon as the file is opened (andreadsome()
on such implementations reads data, potentially, but not necessarily, the entire file), while other implementations only read from file when an actual input operation is requested (andreadsome()
issued after file opening never extracts any characters). Likewise, a call tostd::cin.readsome()
may return all pending unprocessed console input, or may always return zero and extract no characters.
However, if I try this with:
std::cin >> buffer.data();
Then I can extract the console input. In order to get the behavior you are seeking, I would use std::istream::get()
, and check the eof
and fail
bits in your while loop.
回答2:
readsome() terminates when its buffer is exhausted, in order to avoid delays. If you don't already have data waiting for the call by the time you execute it, it won't read anything. It won't wait for you.
来源:https://stackoverflow.com/questions/24700586/stdcin-readsome-always-reading-0-bytes