📜  cpp 执行命令 - C++ 代码示例

📅  最后修改于: 2022-03-11 14:44:58.896000             🧑  作者: Mango

代码示例1
//----------------------------------
//  CREDIT: gregpaton08 on stack overflow
//  https://stackoverflow.com/questions/478898/how-do-i-execute-a-command-and-get-the-output-of-the-command-within-c-using-po
//----------------------------------
#include 
#include 
#include 
#include 
#include 
#include 

std::string exec(const char* cmd) {
    std::array buffer;
    std::string result;
    std::unique_ptr pipe(popen(cmd, "r"), pclose);
    if (!pipe) {
        throw std::runtime_error("popen() failed!");
    }
    while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
        result += buffer.data();
    }
    return result;
}