c ++:subprocess输出到stdin [英] c++: subprocess output to stdin
问题描述
假设我想从我的程序中调用子进程,并且我想将该子进程的输出读入我的程序。
Suppose I want to call a subprocess from within my program, and I want to read the output from that subprocess into my program.
这里是一个简单的方法这样做:
Here is a trivial way to do that:
//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
我们都知道i / o操作计算速度慢。为了加快速度,我想跳过写到文件然后从文件读取步骤,而是将这个子进程的输出直接重定向到 stdin / strong>(或其他流)
We all know that i/o operations are computationally slow. To speed this up, I would like to skip the write-to-file-then-read-from-file step, and instead redirect the output of this sub-process directly into stdin (or some other stream)
我该如何做?如何跳过i / o操作?
How would I do this? How do I skip the i/o operation?
注意:许多程序在运行时向stdout输出一些诊断信息,并将一个干净的输出写入stdout (例如:stdout:step1 ... done,step2 ... done,step3..done-o file-out:幻数是:47.28),所以忽略-o参数,输出将自动重定向到stdout不一定有帮助...
Note: many programs spit out some diagnostic stuff into stdout while they run, and write a clean version of the output to stdout (ex: stdout: "step1...done, step2...done, step3..done" -o file-out: "The magic number is: 47.28"), so ignoring the "-o " argument and trusting that output will be automatically re-directed to stdout isn't necessarily helpful...
感谢所有提前。
推荐答案
使用 popen
跳过文件,通过内存缓冲区获取命令的输出。
Using popen
skips the file, and gets you command's output through an in-memory buffer.
#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;
}
这篇关于c ++:subprocess输出到stdin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!