zoukankan      html  css  js  c++  java
  • 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
      ", 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
      ", cmd);
      
              return 0;
      }

     有关在 windows 上实现的过程及源码详见:C程序中获得命令行输出结果

  • 相关阅读:
    nginx升级步骤
    对一些信息进行正则校验
    对list对象进行排序
    文件上传实现ajax假异步
    解决springmvc+fastjson返回页面出现乱码问题
    php opcode缓存
    node.js 抓取
    mysql 好文章
    rabbitmq 安装
    配置安装nginx
  • 原文地址:https://www.cnblogs.com/sylar5/p/6644870.html
Copyright © 2011-2022 走看看