执行命令并获取输出:popen和pclose未定义

4

此回答所解释的那样,我尝试在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.
1个回答

7

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

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

使用:

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

有没有一些标准的包含文件可以避免这种情况? - Jean-François Fabre

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接