使用popen的好處只是讀取命令產生的輸出,或者系統中有更多的好處或優點。popen vs C中的系統功能
考慮下面兩個方案:
計劃1:
#include <stdio.h>
int main()
{
FILE *more,*who;
if (!(more = popen("more", "w")))
{
printf("Command `more` not found!");
return -1;
}
if (!(who = popen("who", "r")))
{
printf("Command `who` not found!");
return -1;
}
while (!feof(who))
{
char buffer[100];
if (fgets(buffer, 100, who) != NULL)
{
fputs(buffer, more);
}
}
fclose(more);
fclose(who);
return 0;
}
方案2:
#include <unistd.h>
int main()
{
system("who|more");
return 0;
}
我爲什麼要使用PROGRAM1如果我能做到同樣的事情在一個線如在Program2中所做的那樣。
如果你做了一點研究,你會遇到[這個堆棧溢出線程](http://stackoverflow.com/questions/8538324/what-is-the-difference-between-popen-and-system-在-C)。 – 2013-05-07 06:46:33
請注意,您應該在使用popen()打開的文件描述符上使用pclose()。 – 2013-11-16 12:11:41