Home >Backend Development >C++ >How to Capture Real-time System Command Output in C/C using `popen`?

How to Capture Real-time System Command Output in C/C using `popen`?

Linda Hamilton
Linda HamiltonOriginal
2024-12-05 14:43:15565browse

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);
  • command: Specifies the system command to execute.
  • type: Indicates the mode to open the stream. Typically, use "r" for reading (stdout) or "w" for writing (stdin).

Process:

  1. To open a stream for reading the command's output, use:
FILE *stream = popen(command, "r");
  1. Read the stream as you would any other input source:
char buffer[1024];
while (fgets(buffer, sizeof(buffer), stream) != NULL) {
    // Process each line of output
}
  1. Close the stream when done:
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn