C++ Launch Command Line App and Capture Output


In windows, the pipe functions are defined as _popen() and _pclose(), however on Linux they are popen() and pclose(). The #ifdef WIN32 codeblock allows the program to compile on both windows and linux without changing any of the code. In order to get this block of code running on your operating system, don't forget to call 'dir /b' on windows, and 'ls -1' on linux.

Unix C libraries define a number of functions for launching processes like fork(), exec() and system(). However these launch a process from a C program and never return. Windows provides ShellExec() which does the same thing. There are times when you want to both launch a process, wait for it to return, and capture the output. The following code does just that.
#include <stdio.h>
#include <stdlib.h>
 
#ifdef WIN32
FILE *popen ( const char* command, const char* flags) {return _popen(command,flags);}
int pclose ( FILE* fd) { return _pclose(fd);}
#endif
 
int main(int argc, char* argv[])
{
    char psBuffer[128];
    FILE *iopipe;
 
    if( (iopipe = popen( "dir /b", "r" )) == NULL )
        exit( 1 );
 
    while( !feof( iopipe ) )
    {
        if( fgets( psBuffer, 128, iopipe ) != NULL )
            printf( psBuffer );
    }
 
    printf( "\nProcess returned %d\n", pclose( iopipe ) );
    return 0;
}


The only problem I have had with this, is that sometimes the application you call requires input, like "dir |more". This sample program only accounts for output, and not input. It may be possible to use fputs() to take care of this. I will leave that to the reader to experiment with.
code snippets are licensed under Creative Commons CC-By-SA 3.0 (unless otherwise specified)