zoukankan      html  css  js  c++  java
  • C++ execute linux cmd and retrieve the output

    
    

    #include <iostream>
    #include <stdlib.h>
    #include <stdio.h>
    #include <vector>
    #include <stdexcept>
    #include <string>
    #include <sstream>
    #include <algorithm>



    void
    execLinuxCmd(const char *cmd, vector<string> &vec) { char buffer[128]; FILE *pipe = popen(cmd, "r"); if (!pipe) { throw std::runtime_error("popen() failed!"); } stringstream ss; try { while (fgets(buffer, sizeof buffer, pipe) != NULL) { string lineResult(buffer); const char * charFullName=lineResult.c_str(); char *fullName=(char*)malloc(128); realpath(charFullName,fullName); ss<<fullName<<endl; string strResult=ss.str(); strResult=strResult.substr(0,strResult.length()-2); // strResult.erase(std::remove(strResult.begin(),strResult.end(),' '),strResult.end()); vec.push_back(strResult); ss=stringstream(); free(fullName); } } catch (...) { cout<<"exception"<<endl; pclose(pipe); throw; } pclose(pipe); }
    void cmd18()
    {
        string cmd="cd /home/fred/Work/NP/20211024/cpp;ls -r;";
        vector<string> vec;
        execLinuxCmd(cmd.c_str(),vec);
        vector<string>::iterator itr=vec.begin();
        while(itr!=vec.end())
        {
            cout<<*itr<<endl;
            itr++;
        }
    }

     

    /home/fred/Work/NP/20211024/cpp/h3.cpp
    /home/fred/Work/NP/20211024/cpp/h2.cpp
    /home/fred/Work/NP/20211024/cpp/h1.cpp
    /home/fred/Work/NP/20211024/cpp/h1

  • 相关阅读:
    mac 显示隐藏文件 快捷键
    Swift常用内置函数介绍
    MacOS Catalina 虚拟机VMware Fusion 重装教程 和问题
    swift 时间显示格式
    mybatis自测错题总结
    Spring核心概念和案例
    MyBatis注解
    MyBatis缓存
    关联查询
    智能标签
  • 原文地址:https://www.cnblogs.com/Fred1987/p/15455729.html
Copyright © 2011-2022 走看看