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

原文地址:https://www.cnblogs.com/Fred1987/p/15455729.html