【问题标题】:Continuously reading piped bytes from a file从文件中连续读取管道字节
【发布时间】:2014-02-21 02:47:22
【问题描述】:

我有以下代码将字节从文件传输到我的 C++ 应用程序:

  char *buffer = new char[SIZE];

  while (!std::cin.eof()) {
      std::cin.read(buffer, SIZE);
      for(int i=0; i<SIZE; i++){
        std::cout << buffer[i] << std::endl;
      }
  }

但是,问题是我只输出/读取管道的前 SIZE 个字节。如何从管道大小大于 SIZE 的管道中读取所有字节?

【问题讨论】:

  • 请阅读 istream 文档。你应该检查返回值!
  • cplusplus.com/reference/ios/ios/eof 似乎暗示我所做的可以吗? :s
  • 没有。你还没有。在读取请求的大小之前,读取方法可能会到达 EOF。
  • 是吗?如果我有一个 45 字节的流大小并且我一次读取 10 个字节,那么最后一次读取中间会有 EOF?
  • 是的,read operation 只会部分填充缓冲区。

标签: c++ linux unix pipe


【解决方案1】:

gcount() 在读操作后不检查。 正确方法:

while (!std::cin.eof()) {
      std::cin.read(buffer, SIZE);
      for(int i=0; i<cin.gcount(); i++){
        std::cout << buffer[i] << std::endl;
      }
  }

【讨论】:

    猜你喜欢
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多