Dakshina`s Blog

My views..
Friday Dec 01, 2006

Getting the output of a shell command from a C program using popen

 Sometimes its necessary to access the output of a shell command(more than just the return value) in a C program. One way could be to redirect it to a file and then access it .The other would be by using the popen function.

#include<stdio.h>

main(){
  char  cmd[80];
  FILE *fptr;
  char out[256];
  int ret;
  strcpy(cmd,"ls -l");
  fptr = popen(cmd, "r");
  while(1){
        fgets(out, 256, fptr);
        if(feof(fptr)) break;
        puts(out);
  }
 ret = pclose(fptr);
}


/* Noted tested with S10 gcc only ..*/

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed

Archives
Links
Referrers