C:运行系统命令并获取输出?我想在linux中运行一个命令,并返回它输出的文本,但我不希望这个文本打印到屏幕上。有没有比制作临时文件更优雅的方式?
3 回答

jeck猫
TA贡献1909条经验 获得超7个赞
你想要“ popen ”功能。这是运行命令“ls / etc”并输出到控制台的示例。
#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)-1, fp) != NULL) { printf("%s", path); } /* close */ pclose(fp); return 0;}

富国沪深
TA贡献1790条经验 获得超9个赞
通常,如果该命令是外部程序,您可以使用操作系统来帮助您。
command > file_output.txt
所以你的C代码会做类似的事情
exec("command > file_output.txt");
然后,您可以使用file_output.txt文件。
- 3 回答
- 0 关注
- 860 浏览
添加回答
举报
0/150
提交
取消