我想在Linux中运行一个命令并获取它的输出文本,但不希望将这些文本打印到屏幕上。是否有比创建临时文件更加优雅的方法?
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[] )
{
FILE *fp;
char path[1035];
/* Open the command for reading. */
fp = popen("/bin/ls /etc/", "r");
if (fp == NULL) {
printf("Failed to run command\n" );
exit(1);
}
/* Read the output a line at a time - output it. */
while (fgets(path, sizeof(path), fp) != NULL) {
printf("%s", path);
}
/* close */
pclose(fp);
return 0;
}
fgets(path, sizeof(path), fp)
而不是sizeof(path)-1
。阅读手册。 - user102008int status
没有被使用。不是什么大问题。编辑:我已经移除了它。 - arr_sea