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