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.
#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;
}
Maybe popen is your solution?
精彩评论