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.
我正在Android / Linux下编写一个运行系统命令的C程序。该命令将一些文本输出到stdout,我正在尝试将输出捕获到字符串或字符数组中。
For example:
system("ls");
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.
会将当前目录的内容列为stdout,我希望能够以C编程方式将该数据捕获到C中。
How do I do this?
我该怎么做呢?
Thanks.
1 个解决方案
#1
15
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.
你想用popen。它返回一个流,就像fopen一样。但是,您需要使用pclose关闭流。这是因为pclose负责清理与启动子进程相关的资源。
FILE *ls = popen("ls", "r");
char buf[256];
while (fgets(buf, sizeof(buf), ls) != 0) {
/*...*/
}
pclose(ls);
#1
15
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.
你想用popen。它返回一个流,就像fopen一样。但是,您需要使用pclose关闭流。这是因为pclose负责清理与启动子进程相关的资源。
FILE *ls = popen("ls", "r");
char buf[256];
while (fgets(buf, sizeof(buf), ls) != 0) {
/*...*/
}
pclose(ls);