1. 程式人生 > >【c/c++】如何呼叫【linux】shell命令列命令並獲取命令列的輸出內容

【c/c++】如何呼叫【linux】shell命令列命令並獲取命令列的輸出內容

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