溫馨提示×

c++中執(zhí)行cmd命令的輸入輸出重定向如何實(shí)現(xiàn)

c++
小樊
83
2024-09-15 18:47:55
欄目: 編程語言

在C++中,你可以使用popen()函數(shù)來執(zhí)行CMD命令并獲取其輸出

#include<iostream>
#include <fstream>
#include<string>

int main() {
    // 要執(zhí)行的CMD命令
    std::string cmd = "dir";
    
    // 創(chuàng)建一個文件流,用于讀取命令執(zhí)行結(jié)果
    FILE* pipe = popen(cmd.c_str(), "r");
    if (!pipe) {
        std::cerr << "Failed to execute command."<< std::endl;
        return 1;
    }

    // 從文件流中讀取命令執(zhí)行結(jié)果
    char buffer[128];
    std::string result;
    while (fgets(buffer, sizeof(buffer), pipe)) {
        result += buffer;
    }

    // 關(guān)閉文件流
    pclose(pipe);

    // 輸出命令執(zhí)行結(jié)果
    std::cout << "Command output: "<< std::endl<< result<< std::endl;

    return 0;
}

這個示例中,我們使用popen()函數(shù)執(zhí)行了dir命令,然后從返回的文件流中讀取命令執(zhí)行結(jié)果。最后,我們將結(jié)果輸出到控制臺。

注意:popen()函數(shù)在Windows和Linux平臺上都可以使用,但是在某些系統(tǒng)上可能需要安裝額外的庫。在使用前,請確保你的系統(tǒng)支持該函數(shù)。

0