C++中,如何執行一個控制檯命令並返回結果到字符串string中

在寫作c、c++控制檯程序時,我們可以直接調用控制檯下的命令,在控制檯上輸出一些信息。

調用方式爲 system(char*);

例如,在控制檯程序中,獲得本機網絡配置情況。

int main(){

system("ipconfig");

return 0;

}

但是,如果我們想保存調用命令的輸出結果呢?

這裏給大家介紹一種方法:

#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;
}
如果是在windows系統下,請用_popen, _pclose替換popen, pclose。

這個函數中,輸入的是命令的名字,返回的是執行的結果。

從一個國外網站上看來的:http://stackoverflow.com/questions/478898/how-to-execute-a-command-and-get-output-of-command-within-c

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章