Home >Backend Development >C++ >How Can I Capture stdout from a system() Command in C/C ?
Capturing stdout from a system() command in C/C
Upon executing a system command using system(), it becomes essential to capture its output for further processing. C/C offers various approaches to achieve this, with the popen() function emerging as a reliable solution.
popen() Function
The popen() function opens a pipe from the shell and launches a process by executing the specified command. It returns a stream pointer FILE *connected to the pipe, enabling read and write operations.
Syntax and Usage
The syntax of popen() is as follows:
#include <stdio.h> FILE *popen(const char *command, const char *type);
where:
To capture the stdout of a system command, use:
FILE *fp = popen(command, "r");
The FILE *fp represents a stream connected to the stdout of the command. You can then use fgetc(), fgets(), or other stream manipulation functions to read the output.
Example
char buffer[BUFSIZ]; FILE *fp = popen("ls", "r"); while (fgets(buffer, BUFSIZ, fp) != NULL) { printf("%s", buffer); } pclose(fp);
Closing the Pipe
Once you have finished reading the output, it's essential to close the pipe using pclose() to release the associated resources:
int status = pclose(fp);
Note: capturing stdout using popen() inherits any errors encountered by the external command. Consider checking the return value of pclose() to detect any errors.
The above is the detailed content of How Can I Capture stdout from a system() Command in C/C ?. For more information, please follow other related articles on the PHP Chinese website!