我使用C ++代码并使用了辅助工具pv(管道查看器)进行了简单测试. 代码是:
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); } }我执行:
pv /dev/urandom | ./a.out通过pv,我注意到readsome从不读取任何内容.我想念什么?
Through pv, I notice that readsome never reads anything. What am I missing?
推荐答案请参阅 cppreference ,尤其是在注释"下.
Please see cppreference, especially under "Notes".
此功能的行为是高度特定于实现的.例如,当与std::ifstream一起使用时,某些库实现会在文件打开后立即用数据填充底层的filebuf(此类实现上的readsome()可能会读取数据,但不一定会读取整个文件),而其他实现则仅在请求实际输入操作时才从文件读取(并且在打开文件后发出的readsome()从未提取任何字符).同样,对std::cin.readsome()的调用可能返回所有未处理的未处理控制台输入,或者可能始终返回零并且不提取任何字符.
The behavior of this function is highly implementation-specific. For example, when used with std::ifstream, some library implementations fill the underlying filebuf with data as soon as the file is opened (and readsome() 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 (and readsome() issued after file opening never extracts any characters). Likewise, a call to std::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();然后,我可以提取控制台输入.为了获得您要查找的行为,我将使用std::istream::get(),并检查while循环中的eof和fail位.
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.
更多推荐
std :: cin.readsome总是读取0个字节
发布评论