Recently I had to parse some command line output inside a C++ program. Executing a command and getting just the exit status is easy using
std::system, but also getting output is a bit harder and OS specific. By using
popen, a POSIX
Cfunction we can get both the exit status as well as the output of a given command. On Windows I’m using
_popen, so the code should be cross platform. This article starts off with a stack overflow example to get just the output of a command and builds on that to a safer version (null-byte handling) that returns both the exit status as well as the command output. It also involves a lot of detail on
fgetsand how to handle binary data.