【发布时间】:2013-05-07 05:53:27
【问题描述】:
是使用popen的好处只是读取命令产生的输出,或者popen比系统有更多的好处或优势。
考虑以下两个程序:
方案一:
#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;
}
方案二:
#include <unistd.h>
int main()
{
system("who|more");
return 0;
}
如果我可以在一行中完成与 Program2 中相同的操作,为什么还要使用 Program1。
【问题讨论】:
-
如果你做一点研究,你会遇到this Stack Overflow thread。
-
请注意,您应该在使用 popen() 打开的文件描述符上使用 pclose()。