如this answer中所述,我尝试执行一个Windows命令,并在Visual Studio项目中获取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.
答案 0 :(得分:3)
由于使用了Microsoft编译器,因此在popen
和pclose
的开头需要一个下划线。替换:
std::shared_ptr<FILE> pipe(popen(cmd, "r"), pclose);
使用:
std::shared_ptr<FILE> pipe(_popen(cmd, "r"), _pclose);