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

how to read command output line by line in gcc in windows just as with the standard input?

本文关键字:标准输入 一样 输出 中的 windows gcc 命令 读取 逐行      更新时间:2023-10-16

这就是我尝试的:

#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-edit:好吧,我知道,我错过了这不是GCC库,它的名称和以前一样,但这是单独的下载:http://pstreams.sourceforge.net/

我知道如何使用缓冲区并在单行上获得整个输出(如这里:https://stackoverflow.com/a/478960/393087),然后用n分解行,得到我的数组,但这里的要点是,我必须在输入一进来就提供输出

此外,我还尝试了以下示例:https://stackoverflow.com/a/313382/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 typeifstream ins(fileno(fp)); // ifstream ctor using a file descriptor

你不能这样做:

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;
}

:)