getting the output of external program to c++ code

2019-08-08 03:23发布

This question already has an answer here:

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

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

how to write that in c++

标签: c++ linux
1条回答
走好不送
2楼-- · 2019-08-08 03:50

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

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.

查看更多
登录 后发表回答