Monday, August 29, 2011

calling shell in C and getting output

To execute shell command from C and get the output to C we need to use the

popen command  in C.


include <stdio.h>
2 
3int main(void) {
4    FILE *in;
5    extern FILE *popen();
6    char buff[512];
7 
8    if(!(in = popen("ls -sail""r"))){
9        exit(1);
10    }
11 
12    while(fgets(buff, sizeof(buff), in)!=NULL){
13        printf("%s", buff);
14    }
15    pclose(in);
16 
17}

As stated in the program this can be used to get the output to the command.