How to get the result from system () in C / C ++

Possible duplicate:
How to start an external program with C and analyze its output?

Hello,

Can someone tell us how to get the result when the system () function is executed?

In fact, I wrote a C ++ program that displays the IP address of a computer called "ipdisp", and I want when the sever program runs this ipdisp program, the IP address of the display is indicated on the server. So is this possible? if so, how?

thank you for your responses

+5
source share
2 answers

Yes, you can do it, but you cannot use system(), you have to use popen(). Sort of:

FILE *f = popen("ipdisp", "r");
while (!feof(f)) {
    // ... read lines from f using regular stdio functions
}
pclose(f);
+6

. , . , , ... popen() - . :

#include <stdlib.h>
#include <stdio.h>
void
die( char *msg ) {
    perror( msg );
    exit( EXIT_FAILURE );
}

int
main( void )
{
    size_t len;
    FILE *f;
    int c;
    char *buf;
    char *cmd = "echo foo";
    char *path = "/tmp/output"; /* Should really use mkstemp() */

    len = (size_t) snprintf( buf, 0,  "%s > %s", cmd, path ) + 1;
    buf = malloc( len );
    if( buf == NULL ) die( "malloc");
    snprintf( buf, len, "%s > %s", cmd, path );
    if( system( buf )) die( buf );
    f = fopen( path, "r" );
    if( f == NULL ) die( path );
    printf( "output of command: %s\n", buf );
    while(( c = getc( f )) != EOF )
        fputc( c, stdout );
    return EXIT_SUCCESS;
}

... ( , , , ..).

+1

All Articles