tags:

views:

143

answers:

2

Possible Duplicate:
How can I run an external program from C and parse its output?

Hi,

Could someone please tell us how to capture a result when executing system() function ?

Actually I wrote a c++ program that displays the machine's IP address, called "ipdisp" and I want when a sever program executes this ipdisp program, the server captes the display IP address. So, is this possible? if yes, how?

thanks for your replies

+6  A: 

Yes, you can do this but you can't use system(), you'll have to use popen() instead. Something like:

FILE *f = popen("ipdisp", "r");
while (!feof(f)) {
    // ... read lines from f using regular stdio functions
}
pclose(f);
Greg Hewgill
thanks a lot! just to clarify please . the variable that display is e.g. (char *xx1;) so how can we get xx1? thanks again!
make
Assuming `ipdisp` writes its output to stdout, you'll be able to read its stdout through the file `f` above. Use `fgets` or similar.
Greg Hewgill
thanks! Actually I have two variables: hostname and ipaddress and I want to capte the ipaddress. is the stdout takes the last displayed one? thanks again
make
I wrote a small program as you said, but when I read stdout I get this : Server IP-Address is: 192.168.0.113 and it doesn't display anything. So is it possible to get only this "192.168.0.113". thanks!
make
+1  A: 

Greg is not entirely correct. You can use system, but it's a really bad idea. You can use system by writing the output of the command to a temporary file and then reading the file...but popen() is a much better approach. For example:

#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;
}

There are lots of problems with this approach...(portability of the syntax for redirection, leaving the file on the filesystem, security issues with other processes reading the temporary file, etc, etc.)

William Pursell