在寫作c、c++控制臺程序時,我們可以直接調用控制臺下的命令c語言輸出到控制臺,在控制臺上輸出一些信息。
調用方式為 (char*);
例如,在控制臺程序中,獲得本機網絡配置情況。
int main(){
("");
0;
}
但是,如果我們想保存調用命令的輸出結果呢?
這里給大家介紹一種方法:
#include

#include
#include
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;
}
如果是在系統下,請用, 替換popen, 。
這個函數中,輸入的是命令的名字c語言輸出到控制臺,返回的是執行的結果。
從一個國外網站上看來的: