得到外部程序的输出到c ++代码 [英] getting the output of external program to c++ code

查看:126
本文介绍了得到外部程序的输出到c ++代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在编写一个可以将一些字符串传递给外部程序并获得反馈的c ++代码。

I'm struggling in writing a c++ code that would pass some "string" to an external program and get the feedback.

说我想传递一个c ++代码到gcc并将错误消息恢复到我的原始代码

say for example I want to pass a c++ code to gcc and get the error messages back to my original code

如何在c ++中编写

推荐答案

有两种方法。简单的方法,如果你只想读取外部程序的输出,就是使用 popen

There are two ways of doing it. The simple way, if you just want to read the output from an external program, is to use popen:

FILE* fp = popen("/some/command argument1 argument2", "r");

char input[256];
while (fgets(input, sizeof(input), fp))
{
    std::cout << "Got input from command: " << input;
}






(以及 popen 如何在幕后工作)是创建一个新的匿名管道( pipe ),一个新进程( fork ),设置新进程的标准输出以使用管道,然后 exec 子进程中的程序。然后,您可以从管道的读端读取程序的输出。这是更灵活,和推荐的方式(即使它更复杂的设置)。它也是唯一的方式,如果你想能够做双向通信,即写入外部程序标准输入从其输出读取。


The other more complicated way (and how popen works behind the scenes) is to create a new anonymous pipe (with pipe), a new process (with fork), set up the standard output of the new process to use the pipe, and then exec the program in the child process. Then you can read the output from the program from the read-end of the pipe. This is more flexible, and the recommended way (even though it's more complicated to set up). It's also the only way if you want to be able to do two-way communication, i.e. write to the external programs standard input and read from its output.

这篇关于得到外部程序的输出到c ++代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆