【C/C++】程序中如何执行操作系统命令?

   在我们编写C或者C++程序时候,有时候会碰到要求执行操作系统命令或者其他应用程序,同时要么需要获取命令执行的输出,要么不需要获取命令执行的输出,针对这两点,我分别各介绍一方式

  1:  方法一: system 函数

      直接上示例大家更容易理解:

       if (0 != system("/bin/echo \"hello world\""))
       {
            printf("%s", "system failed");;
       }

  2:  方法二: popen 函数

      同上,直接上示例:

     char    tmpstring[512] = {0};

     std::string cmdstring = "/bin/echo \"hello world\" "

     FILE* fp = popen(cmdstring.c_str(), "r");

     if (NULL == fp)
     {
         printf("%s", "popen failed");
         exit(-1);
     }

     memset_s(tmpstring, sizeof(tmpstring), 0, sizeof(tmpstring));

    if (fgets(tmpstring, (int)sizeof(tmpstring), fp) != NULL)

    {

         tmpstring[strlen(tmpstring) - 1] = 0;

    }

    pclose(fp);
    fp = NULL;

    

   在我们编写C或者C++程序时候,有时候会碰到要求执行操作系统命令或者其他应用程序,同时要么需要获取命令执行的输出,要么不需要获取命令执行的输出,针对这两点,我分别各介绍一方式

猜你喜欢

转载自blog.csdn.net/m0_38130105/article/details/83786435
今日推荐