Home > Backend Development > C++ > How Can I Capture stdout from a system() Command in C/C ?

How Can I Capture stdout from a system() Command in C/C ?

Linda Hamilton
Release: 2024-12-10 02:51:09
Original
942 people have browsed it

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

where:

  • command is the system command to be executed.
  • type specifies the type of connection to the pipe: "r" for reading or "w" for writing.

To capture the stdout of a system command, use:

FILE *fp = popen(command, "r");
Copy after login

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

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

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!

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