- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
Advertisements