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.

1 Answer 1

20

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);
Sign up to request clarification or add additional context in comments.

2 Comments

This only gets the output stream, ho to get the error stream too?
@ShashankSingh tio.run/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.