My Tech notes: popen Useful C function to Read Output of Command
Subscribe

Unix Documentation

Free Online Unix Training Materials

Lists many links to free Unix training materials.

Pointers and Arrays Materials

Pointers and Arrays materials Explained for C beginners

C FAQ and General Questions C Interview Questions

Powered By

Free XML Skins for Blogger

Powered by Blogger

Wednesday, August 13, 2008

popen Useful C function to Read Output of Command

"popen" Easy way to read the output of the command from the c program,

In our applications we do like this to read the output of the command.
Eg: This example prints the size of the given file.
main(int argc, char *argv[])
{
char cmd[100];
FILE *fp1_p;
unsigned int size;
if(argc < 2) {
printf("usage: %s filename\n", argv[0]);
return;
}
sprintf(cmd, "ls -l %s | awk -F \" \" \'{print $5}\' > egSize.txt", argv[1]);
system(cmd);
fp1_p = fopen("egSize.txt", "r");
fscanf(fp1_p, "%d", &size);
printf("%s file size is %d\n", argv[1], size);
close(fp1_p);
}

Easy way to do the same thing with popen.
main(int argc, char *argv[])
{
char cmd[100];
FILE *fp1_p;
unsigned int size;
if(argc < 2) {
printf("usage: %s filename\n", argv[0]);
return;
}
sprintf(cmd, "ls -l %s | awk -F \" \" \'{print $5}\'", argv[1]);
fp1_p = popen(cmd, "r");
fscanf(fp1_p, "%d", &size);
printf("%s file size is %d\n", argv[1], size);
pclose(fp1_p);
}

-> man popen for more information on popen.

No comments:

Post a Comment