Je t’embrasse Salutations from Silicon Valley, California


Pythons getoutput() ported to C/C++

I ran into an issue the other day where, being an avid Python programmer, I was trying my best in C/C++ to mimic the command-output-capturing capabilities of Python.
In an effort to produce a C/C++ version of the Python commands.getoutput() function, I ended up with the following:

#include <stdio.h>
#include <string.h>
#include <sys/wait.h>

command_output(const char *cmd, char *output, int readlen)
    FILE *fp;
    int retval=0;
    memset(output, 0, readlen);

    /* return error if pipe error */
    if ( !(fp = (FILE*)popen(cmd, "r")) ) return 1;

    if (fread(output, readlen, 1, fp) != 1) {
        retval = pclose(fp);
        if (WIFEXITED(retval)) return 0;
        /* Command did not execute correctly, or was killed */
        return 2;

    /* guarantee NULL termination */
    output[readlen - 1] = '\0';
    return 0;

Although it does require a bit more information than the Python equivalent, it is extremely handy to have in one's toolbox. Especially when interactions are forced between your C/C++ internals, and preexisting applications. Note that this code operates with the same permissions as the application, thus cannot execute anything that the application does not have permission to execute.

Filed under: C/C++ No Comments