1

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.

BD at Rivenhill
  • 12,395
  • 10
  • 46
  • 49
  • 1
    Lots of duplicates: http://stackoverflow.com/questions/125828/best-way-to-capture-stdout-from-a-system-command-so-it-can-be-passed-to-another http://stackoverflow.com/questions/1583234/c-system-function-how-to-collect-the-return-value-of-the-issued-command http://stackoverflow.com/questions/671461/how-can-i-execute-external-commands-in-c-linux and so on from http://stackoverflow.com/search?q=popen+[c%2B%2B] – dmckee --- ex-moderator kitten Apr 11 '10 at 20:01

2 Answers2

5
#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
  • 57,473
  • 20
  • 96
  • 131
2

Maybe popen is your solution?

R Samuel Klatchko
  • 74,869
  • 16
  • 134
  • 187
xcramps
  • 1,203
  • 1
  • 9
  • 9