【c/c++】如何呼叫【linux】shell命令列命令並獲取命令列的輸出內容
阿新 • • 發佈:2019-02-10
#include <stdio.h> #include <string.h> 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) { // 可以通過這行來獲取shell命令列中的每一行的輸出 // printf("%s", buf_ps); strcat(result, buf_ps); if(strlen(result)>1024) break; } pclose(ptr); ptr = NULL; } else { printf("popen %s error\n", ps); } } int main() { char result[1024]={0}; executeCMD("python /usr/xhh/pythonprojects/Demo1.py [1,2,3]", result); // 這行是將每一行的輸出拼接之後獲取到了result字串中了 printf("%s", result); return 0; }