std::istream::read does not block?

std::istream::read does not block?

本文关键字:block not read istream std does      更新时间:2023-10-16

简而言之,当我传输的数据少于它需要的数据时,它不会等待。源代码:

#include <iostream>
using namespace std;
int main(){
  char buf[1024];
  cin.read(buf, 5);
  buf[5]='';
  cout<<buf<<endl;
}

g++foo.cpp
echo"123"|/a.out

123

如果我直接运行./a.out,程序将等待我输入5个字符。

read读取字符,直到它读取指定数量的字符或遇到流的末尾。

  • 当您通过管道传输数据时,系统知道流何时结束并发送结束流信号
  • 当您通过交互式设备发送数据时,系统不会知道你是否发送了所有想要的数据,或者你想输入更多,所以它询问您,等待输入。您可以发送流结束信号在Linux上按Ctrl+D手动指定是任何进一步的输入

如果您可以使用stream.fail()检查上次操作是否失败(没有读取所有请求的字符(,并使用stream.gcount()检查实际读取的字符数。

我已将您的代码更新为以下

#include <iostream>
using namespace std;
int main(){
  char buf[1024];
  do{
    cin.read(buf, 5);
    buf[5]=''; // can be moved out of loop (placed after while)
  }while(cin.gcount() < 5);
  cout<< "Result is >" << buf << "<" <<endl;
}

现在程序正在等待,直到至少有5个字符被读取到buf,但您应该理解n也是cin流中的字符,因为用户按下了Enter键