【发布时间】:2014-04-05 16:10:36
【问题描述】:
我试图编译下面的代码(来自https://stackoverflow.com/a/478960/683218)。 编译顺利,如果我用
编译$ g++ test.cpp
但在使用-std=c++11 开关时出错:
$ g++ -std=c++11 test.cpp
test.cpp: In function 'std::string exec(char*)':
test.cpp:6:32: error: 'popen' was not declared in this scope
FILE* pipe = popen(cmd, "r");
^
知道发生了什么吗?
(我正在使用来自 mingw.org 的 mingw32 gcc4.8.1,在 WindowsXP64 上)
代码:
#include <string>
#include <iostream>
#include <stdio.h>
std::string exec(char* cmd) {
FILE* pipe = popen(cmd, "r");
if (!pipe) return "ERROR";
char buffer[128];
std::string result = "";
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
pclose(pipe);
return result;
}
int main() {}
【问题讨论】:
-
与你的当前问题无关,但不要这样做
while (!feof(...)),它不会像你期望的那样工作。原因是EOF标志直到在您尝试从文件末尾之外读取时才会设置,因此您将迭代一次到多次。相反,在您的情况下,只需执行while (fgets(...) != 0)。从 C++ 流中读取时也是如此。
标签: c++ c++11 mingw popen stdio