C/C++ 程序中调用命令行命令并获取命令行输出结果

在 c/c++ 程序中,可以使用 system()函数运行命令行命令,但是只能得到该命令行的 int 型返回值,并不能获得显示结果。例如system(“ls”)只能得到0或非0,如果要获得ls的执行结果,则要通过管道来完成的。首先用popen打开一个命令行的管道,然后通过fgets获得该管道传输的内容,也就是命令行运行的结果。

在linux上运行的例子如下:

  1. 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 的形式,这样将标准错误也读进来。

一个完整的例子是:

  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程序中获得命令行输出结果

posted @ 2017-03-30 11:01  Cyril_Wu  阅读(45125)  评论(3编辑  收藏  举报