Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

วิธีรันคำสั่งและรับ output ใน C++ ด้วย POSIX (popen)


ใช้ popen() และ pclose() สร้าง pipe ไปยัง process อ่าน stdout ของคำสั่ง

โค้ดตัวอย่าง

#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

ทำงานบนระบบ POSIX (Linux, macOS, Unix) Windows อาจต้องใช้ _popen แทน