加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c:subprocess输出到stdin

发布时间:2020-12-16 05:47:46 所属栏目:百科 来源:网络整理
导读:假设我想从我的程序中调用一个子进程,我想把该子进程的输出读入我的程序. 这是一个微不足道的方法: //somefile.cppsystem("sub_process arg1 arg2 -o file.out"); //call the subprocess and have it write to fileFILE *f = std::fopen("file.out","r");//
假设我想从我的程序中调用一个子进程,我想把该子进程的输出读入我的程序.

这是一个微不足道的方法:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读