
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
How to execute a command and get the output of command within 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 and keep appending it to a result string and return this string when the processes exit.
example
#include <iostream> #include <stdexcept> #include <stdio.h> #include <string> using namespace std; string exec(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 (!feof(pipe)) { // use buffer to read and add to result if (fgets(buffer, 128, pipe) != NULL) result += buffer; } pclose(pipe); return result; } int main() { string ls = exec("ls"); cout << ls; }
Output
This will give the output −
a.out hello.cpp hello.py hello.o hydeout my_file.txt watch.py
- Related Articles
- How to execute a command and get output of command within C++ using POSIX?
- How to Save Command Output to a File in Linux?
- How to work with Invoke-Command Scriptblock output?
- How to Get the Path of a Linux Command?
- How can I execute JavaScript at the command prompt?
- C# Program to Get and Print the Command Line Arguments Using Environment Class
- How to convert command output to the Hashtable format in PowerShell?
- Execute a Command in Multiple Directories on Linux
- How to get only the file name using find command on Linux?
- MongoDB profiler output: What is the “command” operation?
- How to exclude PSComputerName property from Invoke-Command output in PowerShell?
- How to exclude the RunSpaceID property from the Invoke-Command output in PowerShell?
- How to get all the processes on the local computer with Get-Process command using PowerShell?
- Give the panel command to start a specific tablespace within a DB2 database.
- How to execute Python multi-line statements in the one-line at command-line?

Advertisements