[c++] 執行 command line 並取得執行結果

http://stackoverflow.com/questions/478898/how-to-execute-a-command-and-get-output-of-command-within-c

用 popen (open pipe)執行 command, 並用 fgets 收結果。如果是在 windows 上,則是改用 _popen, _pclose

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