充分利用标准输出在C系统命令输出 [英] Getting output of a system command from stdout in C
问题描述
我写的Android下的/ Linux下C程序运行系统命令。该命令输出一些文本到stdout,我试图捕获输出到一个字符串或字符数组。
I'm writing a C program under Android/Linux that runs a system command. The command outputs some text to stdout, and I'm trying to capture the output into a string or character array.
例如:
system("ls");
将列出当前目录到标准输出的内容,我希望能够捕获数据到一个变量编程用C
would list the contents of the current directory to stdout, and I would like to be able to capture that data into a variable programmatically in C.
我如何做到这一点?
感谢。
推荐答案
您想要使用的popen
。它返回一个流,如的fopen
。但是,你需要关闭与函数,pclose
流。这是因为函数,pclose
负责清理与启动子进程相关联的资源的照顾。
You want to use popen
. It returns a stream, like fopen
. However, you need to close the stream with pclose
. This is because pclose
takes care of cleaning up the resources associated with launching the child process.
FILE *ls = popen("ls", "r");
char buf[256];
while (fgets(buf, sizeof(buf), ls) != 0) {
/*...*/
}
pclose(ls);
这篇关于充分利用标准输出在C系统命令输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!