tags:

views:

87

answers:

2

Basically, I'm looking for something that will allow me to replicate the following Perl code:

my $fh = new FileHandle;
$fh->open("foo |");
while (<$fh>) {
    # Do something with this line of data.
}

This is in the context of Linux, so a library that is specific to Windows will not help. I know how to write a program that does fork/exec/dup2 and all that basic shell-type jazz, but there are some fiddly details involving terminals that I don't feel like messing around with (and I don't have a copy of "Advanced Programming in the UNIX Environment" or a similar reference handy), so I'm hoping that someone has already solved this problem.

+2  A: 

Maybe popen is your solution?

xcramps
+5  A: 
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>

int main(int argc, char* argv[])
{
    char c;
    FILE* p;

    p = popen("echo hello, world!", "r");
    if( p == NULL ) {
        fprintf(stderr, "Failed to execute shell with \"echo hello, world!\"");
        exit(1);
    }
    while( (c = fgetc(p)) != EOF ) {
        fputc(toupper(c), stdout);
    }
    pclose(p);
    return EXIT_SUCCESS;
}
wilhelmtell
Thanks, I'll probably wrap a C++ class around popen/pclose to do the job.
BD at Rivenhill