zoukankan      html  css  js  c++  java
  • C++ 在linux环境获取命令行返回值

    很多时候我们需要 上层代码需要执行 shell 命令,但还要有返回值,例如需要获取 ls 的返回值

    接下来介绍几种编程语言的获取命令的返回值的方法

    第一种 C++

    代码如下:

    #include <iostream>
    #include <string>
    #include <stdio.h>
     
    int exec_cmd(std::string cmd, std::string &res){
      if (cmd.size() == 0){  //cmd is empty 
        return -1;
      }
     
      char buffer[1024] = {0};
      std::string result = "";
      FILE *pin = popen(cmd.c_str(), "r");
      if (!pin) { //popen failed 
        return -1;
      }
     
      res.clear();
      while(!feof(pin)){
        if(fgets(buffer, sizeof(buffer), pin) != NULL){
          result += buffer;
        }
      }
     
      res = result;
      return pclose(pin); //-1:pclose failed; else shell ret
    }
     
    int main(){
      std::string cmd = "ls -ial";
      std::string res;
     
      std::cout << "ret = " << exec_cmd(cmd, res) << std::endl;
      std::cout << res << std::endl;
     
      return 0;
    }

    运行结果:

    ret = 0
    总用量 164
      17 drwxrwx--- 1 root vboxsf  4096 12月 25 17:09 .
       1 drwxrwx--- 1 root vboxsf  8192 12月 18 17:11 ..
    9325 -rwxrwx--- 1 root vboxsf 14652 12月 25 16:56 a.out
      55 drwxrwx--- 1 root vboxsf  4096 11月  5 16:20 c++
      57 drwxrwx--- 1 root vboxsf  4096 11月  5 15:17 DesignPatterns-master
    7701 -rwxrwx--- 1 root vboxsf 94688 11月  5 09:01 DesignPatterns-master.zip
      79 drwxrwx--- 1 root vboxsf  4096 8月  26 08:59 gototext
    9328 -rwxrwx--- 1 root vboxsf 14652 12月 25 17:09 main
    9324 -rwxrwx--- 1 root vboxsf   722 12月 25 17:07 mianText.cpp
      82 drwxrwx--- 1 root vboxsf  4096 11月  5 16:02 text1
      54 drwxrwx--- 1 root vboxsf  4096 11月  5 15:17 .vscode

    第二种 QT 开启进程的方法

    代码如下:

        // 调用  QProcess 头文件    开个进程绑定信号 在槽函数提取自己想要的数据
    userNameProcess = new QProcess; userNameProcess->start("who"); connect(userNameProcess,SIGNAL(readyReadStandardOutput()) ,this, SLOT(getUserNameProcessSlot())); void MainWindow::getUserNameProcessSlot() { QString temp = userNameProcess->readAll(); Singleton::mutexWiFi.lock(); Singleton::userNameGlobal = temp.mid(0,temp.indexOf(" ",0)); Singleton::mutexWiFi.unlock(); qDebug() << "用户名:" <<Singleton::userNameGlobal<< endl; }

    第三种 python

    代码如下:

    import commands
     
    status, output = commands.getstatusoutput('ls -lt')
     
    print status
    print output
  • 相关阅读:
    Java 数据类型转换
    Perl 日期时间函数(date time)
    find a filename from a filehandle in Perl
    Perl文件读写
    R语言算术运算和逻辑运算
    bash/shell 数学计算
    grep/awk/sed 或者 并且 否定
    关于打印 毕业设计资料
    python 捕获 shell/bash 脚本的输出结果
    推荐几个高质量的图片素材网站
  • 原文地址:https://www.cnblogs.com/wanghuixi/p/12097828.html
Copyright © 2011-2022 走看看