如何在Windows中的gcc中逐行读取命令输出,就像标准输入一样?

时间:2015-04-01 13:59:51

标签: c++ c++11 mingw

这就是我的尝试:

#include <iostream>
#include <string>

int main(int argc, char const *argv[]) {
  using namespace std;
  for (string cin_line; getline(cin, cin_line);) {
    cout << cin_line << endl;
  }
  FILE* pipe = popen("app.exe", "r");
  for (string result_line; getline(pipe, result_line);) {
    cout << result_line << endl;
  }
  pclose(pipe);
  return 0;
}

它不编译,结果是:
no matching function for call to 'getline(FILE*&, std::__cxx11::string&)'

我在这里找到的第二个例子:https://stackoverflow.com/a/10702464/393087 但似乎mingw没有包含pstream:fatal error: pstream.h: No such file or directory - 编辑:确定我知道,我错过了这不是一个GCC库,它的命名就像它一样,但这是单独的下载:{{ 3}}

我知道如何使用缓冲区并在单行上获取整个输出(例如:http://pstreams.sourceforge.net/)然后通过\n爆炸并获取我的数组,但这里的重点是我必须在输入进入后立即提供输出。

此外,我从此处尝试了示例:https://stackoverflow.com/a/478960/393087 - 我已添加main函数:

#include <cstdio>
#include <iostream>
#include <string>

int main(int argc, char const *argv[]) {
  using namespace std;
  FILE * fp ;

  if((fp= popen("/bin/df","r")) == NULL) {
      // error processing and exit
  }
  ifstream ins(fileno(fp)); // ifstream ctor using a file descriptor

  string s;
  while (! ins.eof()){
      getline(ins,s);
      // do something
  }  
  return 0;
}

这也不编译:
error: variable 'std::ifstream ins' has initializer but incomplete type ifstream ins(fileno(fp)); // ifstream ctor using a file descriptor

1 个答案:

答案 0 :(得分:1)

你不能这样做:

FILE* pipe = popen("app.exe", "r");
for (string result_line; getline(pipe, result_line);) {
    cout << result_line << endl;
}
pclose(pipe);

你需要这样做:

#include <boost/noncopyable.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>

FILE* pipe = popen("app.exe", "r");

boost::iostreams::file_descriptor_source 
 source(fileno(pipe), boost::iostreams::never_close_handle);

boost::iostreams::stream<boost::iostreams::file_descriptor_source>
 stream(source, 0x1000, 0x1000); 

string result_line; 
while (getline(stream, result_line)) { 
    cout << result_line << endl;
}

:)