在 c/c++ 程序中,可以使用 system()函數運行命令行命令,但是只能得到該命令行的 int 型返回值,並不能獲得顯示結果。例如system(“ls”)只能得到0或非0,如果要獲得ls的執行結果,則要通過管道來完成的。首先用popen打開一個命令行的管道,然后通過fgets獲得該管道傳輸的內容,也就是命令行運行的結果。
在linux上運行的例子如下:
-
void executeCMD(const char *cmd, char *result) { char buf_ps[1024]; char ps[1024]={0}; FILE *ptr; strcpy(ps, cmd); if((ptr=popen(ps, "r"))!=NULL) { while(fgets(buf_ps, 1024, ptr)!=NULL) { strcat(result, buf_ps); if(strlen(result)>1024) break; } pclose(ptr); ptr = NULL; } else { printf("popen %s error\n", ps); } }
在這段代碼中,參數cmd為要執行的命令行,result為命令行運行結果。輸入的cmd命令最好用... 2>&1 的形式,這樣將標准錯誤也讀進來。
一個完整的例子是:
-
#include <stdlib.h> #include <stdio.h> #include <unistd.h> int main() { FILE* fp = NULL; char cmd[512]; sprintf(cmd, "pwd 2>/dev/null; echo $?"); if ((fp = popen(cmd, "r")) != NULL) { fgets(cmd, sizeof(cmd), fp); pclose(fp); } //0 成功, 1 失敗 printf("cmd is %s\n", cmd); return 0; }
有關在 windows 上實現的過程及源碼詳見:C程序中獲得命令行輸出結果