执行命令并获得输出:popen 和 pclose undefined

Execute a command and get output: popen and pclose undefined

this answer 中所述,我尝试在 visual studio 项目中执行 windows 命令并在 C++ 中获取输出。

std::string executeCommand (const char* cmd) {
    char buffer[128];
    std::string result = "";
    std::shared_ptr<FILE> pipe(popen(cmd, "r"), pclose);
    if (!pipe) throw std::runtime_error("popen() failed!");

    while (!feof(pipe.get())) {
        if (fgets(buffer, 128, pipe.get()) != NULL)
            result += buffer;
    }
    return result;
}

问题是,这不是 compiling.The 给出以下错误:

Error: identifier "popen" is undefined.
Error: identifier "pclose" is undefined.

由于使用微软的编译器,popenpclose开头需要下划线。替换:

std::shared_ptr<FILE> pipe(popen(cmd, "r"), pclose);

与:

std::shared_ptr<FILE> pipe(_popen(cmd, "r"), _pclose);