Home >Backend Development >C++ >How to Capture Real-time System Command Output in C/C using `popen`?
Capturing System Output with popen
Question:
How to effectively capture the real-time output of a system command invoked using system(), such as system("ls"), for further processing in C/C ?
Answer:
The popen function provides an efficient method for capturing output from system commands. Its syntax is:
#include <stdio.h> FILE *popen(const char *command, const char *type); int pclose(FILE *stream);
Process:
FILE *stream = popen(command, "r");
char buffer[1024]; while (fgets(buffer, sizeof(buffer), stream) != NULL) { // Process each line of output }
pclose(stream);
Example:
#include <stdio.h> int main() { FILE *stream = popen("ls", "r"); if (stream != NULL) { char buffer[1024]; while (fgets(buffer, sizeof(buffer), stream) != NULL) { printf("%s", buffer); } pclose(stream); } return 0; }
The above is the detailed content of How to Capture Real-time System Command Output in C/C using `popen`?. For more information, please follow other related articles on the PHP Chinese website!