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

Execute a command and get output: popen and pclose undefined

本文关键字:popen pclose undefined 输出 命令 执行      更新时间:2023-10-16

正如在这个答案中解释的那样,我尝试在visual studio项目中使用c++执行windows命令并获得输出。

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;
}

问题是,这不是编译。给出了以下错误:

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

由于使用了Microsoft编译器,因此需要在popenpclose的开头使用下划线。替换:

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

:

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