popen() এবং pclose() ফাংশন ব্যবহার করে শেল কমান্ড এক্সিকিউট করে এর আউটপুট পাইপের মাধ্যমে পড়া যায়।
উদাহরণ
#include <iostream>
#include <stdexcept>
#include <stdio.h>
#include <string>
using namespace std;
string exec(string command) {
char buffer[128];
string result = "";
FILE* pipe = popen(command.c_str(), "r");
if(!pipe) return "popen failed!";
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
pclose(pipe);
return result;
}
int main() {
string ls = exec("ls");
cout << ls;
}
আউটপুট
a.out hello.cpp hello.py hello.o hydeout my_file.txt watch.py
সতর্কতা: popen POSIX-নির্দিষ্ট (Windows-এ _popen)। বাফার সাইজ এবং এরর হ্যান্ডলিং সাবধানে করুন। আধুনিক C++-এ std::process (C++26 প্রস্তাবিত) বা বूस্ট.প্রসেস ব্যবহার করা ভালো।