16

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.

user1118764
  • 9,255
  • 18
  • 61
  • 113

1 Answers1

19

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);
jxh
  • 69,070
  • 8
  • 110
  • 193
  • 1
    This only gets the output stream, ho to get the error stream too? – Shashank Singh Mar 13 '18 at 11:03
  • 1
    @ShashankSingh https://tio.run/##HY3BCgIhGITvPsWPUWhY0EJ7sRYvBUFvUB02V3eFTUXdS9Gzm9tl@AY@ZuSmlzIvjJXj1Ck4xNQZtx0ahIxN8GqNBULhk8@X6wnWHo7gnVeWYO0cVM1qhxngoDDlSA5tgOekb9W@fnCke5UiKZ1BNG/l9MyUgS@ql6OLivwxlCNNsBBiGUvcbVmcTZ6/@Qc – jxh Mar 13 '18 at 14:37