I am looking for a way to get the output of a command when it is run from within a C++ program. I have looked at using the system() function, but that will just execute a command. Here's an example of what I'm looking for:
std::string result = system( "./some_command" ) ;
I need to run an arbitrary command and get it's output. I've looked at Boost.org but I have not found anything that will give me what I need.
Assuming POSIX, simple code to capture stdout:
Code contributions welcome for more functionality:
https://github.com/ericcurtin/execxx
Getting both stdout and stderr (and also writing to stdin, not shown here) is easy peasy with my pstreams header, which defines iostream classes that work like
popen
:Two possible approaches.
1/ I don't think
popen()
is part of the C++ standard (it's part of POSIX from memory) but it's available on every UNIX I've worked with (and you seem to be targeting UNIX since your command is "./some_command
").2/ On the off-chance that there is no
popen()
, you can usesystem( "./some_command >/tmp/some_command.out" ) ;
then use the normal I/O functions to process the output file.