"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;
{
char cmd[100];
FILE *fp1_p;
unsigned int size;
if(argc < 2) {
printf("usage: %s filename\n", argv[0]);
return;
}
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);
}
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;
{
char cmd[100];
FILE *fp1_p;
unsigned int size;
if(argc < 2) {
printf("usage: %s filename\n", argv[0]);
return;
}
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);
}
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.
Comments