Getting output of a system command from stdout in C

◇◆丶佛笑我妖孽 提交于 2019-12-17 20:03:46

问题


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.

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.

How do I do this?

Thanks.


回答1:


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);


来源:https://stackoverflow.com/questions/11840833/getting-output-of-a-system-command-from-stdout-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!