Execute a Command and Get Output in C++ using POSIX



You can use the popen and pclose functions to pipe to and from processes. The popen() function opens a process by creating a pipe, forking, and invoking the shell. We can use a buffer to read the contents of stdout keep appending it to a result string and return this string when the processes exit.

Example

Here is the following example showing an execution of a command and getting the output of the command within C++ using POSIX.

#include <iostream>
#include <stdexcept>
#include <stdio.h>
#include <string>

using namespace std;

string exec(const string& command) {
 char buffer[128];
 string result = "";

 // Open pipe to file
 FILE* pipe = popen(command.c_str(), "r");
 if (!pipe) {
return "popen failed!";
 }

 // read till end of process:
 while (fgets(buffer, sizeof(buffer), pipe) != NULL) {
 result += buffer;}

// Close the pipe and check if there was an error
int status = pclose(pipe);
if (status == -1) {
 return "Error closing the pipe!";
 }

 return result;
}

int main() {
 string ls = exec("ls");
 cout << ls;
 return 0;
}

Output

This will give the output ?

a.out
hello.cpp
hello.py
hello.o
hydeout
my_file.txt
watch.py
Updated on: 2024-12-03T09:39:51+05:30

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements