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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With