c:subprocess输出到stdin

前端之家收集整理的这篇文章主要介绍了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;
}
原文链接:https://www.f2er.com/c/113686.html

猜你在找的C&C++相关文章