Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting output of a system command from stdout in C

Tags:

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.

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.

like image 677
user1118764 Avatar asked Aug 07 '12 07:08

user1118764


People also ask

How do I copy the output of a command to a file?

Method 1: Use redirection to save command output to file in Linux. You can use redirection in Linux for this purpose. With redirection operator, instead of showing the output on the screen, it goes to the provided file. The > redirects the command output to a file replacing any existing content on the file.

How do I run a terminal command in C?

you could use the system() function available in stdlib. h to run commands. system() executes a command specified in string by calling /bin/sh -c string, and returns after the command has been completed. During execution of the command, SIGCHLD will be blocked, and SIGINT and SIGQUIT will be ignored.

How do you write the output of a command to a variable?

To store the output of a command in a variable, you can use the shell command substitution feature in the forms below: variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name='command' variable_name='command [option ...]

How do I find the shell output?

Get output from shell command using subprocess Launch the shell command that we want to execute using subprocess. Popen function. The arguments to this command is the shell command as a list and specify output and error. The output from subprocess.


1 Answers

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);
like image 121
jxh Avatar answered Oct 07 '22 14:10

jxh