c:subprocess输出到stdin

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

这是一个微不足道的方法

//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(或其他一些流)

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

注意:许多程序在运行时将一些诊断信息发送到stdout,并将输出的干净版本写入stdout(例如:stdout:“step1 … done,step2 … done,step3..done”-o file-out:“魔术数字是:47.28”),所以忽略“-o”参数,相信输出会被自动重定向到stdout并不一定有帮助…

感谢所有提前.

解决方法

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

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...