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
Release: 2024-12-05 14:43:15
Original
614 people have browsed it

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);
Copy after login
  • 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");
Copy after login
  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
}
Copy after login
  1. Close the stream when done:
pclose(stream);
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template