c++ - 执行命令并获得输出 : popen and pclose undefined

标签 c++ visual-studio process

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

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

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

关于c++ - 执行命令并获得输出 : popen and pclose undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38876218/

相关文章:

c++ - 铿锵错误 : note: candidate constructor (the implicit move constructor) not viable:

visual-studio - NuGet 包显示黄色感叹号

C#:如何直接在 java.exe 中执行此命令行?

C-线程和进程-防止僵尸

java - 当我只创建了两个线程时,为什么 `ps` 会列出 > 2 个 Java 线程/"light-weight processes"?

C++:成员指针已初始化?

c++ - 混淆后您的代码有多安全?

c++ - 为什么方法应该返回一个新实例,而不是修改实例本身?

visual-studio - 从 .NET System 类中提取接口(interface)

c - 使用指定的初始值设定项来初始化结构中的二维字符数组初始值设定项会在 VS2013 中发出错误 C2078