/* * Run the 'ls' command and print the output to stdout. * * Compile with * gcc -Wall pipe.c -o pipe * * * Mithenks * Changes added by Jason * */ #include #include #include int main() { FILE *pipe=NULL; char buffer[1024]; int rlen=0; int blen=0; if ( (pipe = popen("ls","r") ) == NULL ) { perror("popen(): "); exit(-1); } /*we subtract 1 so there is always a NULL terminator*/ blen = sizeof(buffer) - 1; while (1) { memset(buffer,0,sizeof(buffer)); if ( (rlen = fread(buffer,blen,1,pipe) ) != 1 ) { /*we have a short read or an error*/ if ( feof(pipe) != 0 ) { fprintf(stderr,"Finished"); printf("%s",buffer); break; } else if ( ferror(pipe) != 0 ) { fprintf(stderr,"Error reading from pipe.\n"); break; } else { /*short read*/ printf("%s",buffer); } } else { /*we got a full buffer*/ printf("%s",buffer); } } if(pipe != NULL) { pclose(pipe); } exit(0); }