c ++:subprocess输出到stdin

cmo*_*cmo 10 c++ redirect stdin stdout

假设我想从我的程序中调用一个子进程,我想将该子进程的输出读入我的程序.

这是一个简单的方法:

//somefile.cpp
system("sub_process arg1 arg2 -o file.out");
           //call the subprocess and have it write to file
FILE *f = std::fopen("file.out", "r");
//.... and so on
Run Code Online (Sandbox Code Playgroud)

我们都知道i/o操作在计算上很慢.为了加快速度,我想跳过write-to-file-then-read-from-file步骤,而是将这个子进程的输出直接重定向stdin(或其他一些流)

我该怎么做?如何跳过i/o操作?

注意:许多程序在运行时将一些诊断内容吐出到stdout中,并将输出的干净版本写入stdout(例如:stdout:"step1 ... done,step2 ... done,step3..done"-o file-out:"神奇的数字是:47.28"),所以忽略"-o"参数并相信该输出将自动重定向到stdout并不一定有用......

感谢所有提前.

das*_*ght 7

使用popen跳过文件,通过内存缓冲区获取命令输出.

#include <iomanip>
#include <iostream>
using namespace std;
const int MAX_BUFFER = 255;
int main() {
    string stdout;
    char buffer[MAX_BUFFER];
    FILE *stream = popen("command", "r");
    while ( fgets(buffer, MAX_BUFFER, stream) != NULL )
        stdout.append(buffer);
    pclose(stream);
    cout << endl << "output: " << endl << stdout << endl;
}
Run Code Online (Sandbox Code Playgroud)

  • @CycoMatto `popen` 是 UNIX 的系统调用,而不是 C/C++ 库函数。这就是为什么它不是命名空间的一部分。 (2认同)