在Linux环境下,在编写程序时,使用popen()
函数执行系统中的命令,并将获取的结果放在程序中使用。
不要忘记最后执行
pclose()
。
函数的原型在文件/usr/include/stdio.h
中
/**
* Linux: CentOS 7.2
* Blog: https://blog.csdn.net/qq_29695701
*/
#include <stdio.h> // popen, fgets, pclose
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
using std::vector;
using std::string;
using std::stringstream;
using std::cout;
using std::endl;
#define MAXLINE 1024
string use_popen(const string& Linux_command, const string& key);
int main(){
string key_line = use_popen("ls -alh", "tmp.txt");
cout << key_line << endl;
return 0;
}
/**
****************************************************************
****************************************************************
* 运行指定的命令,并在得到的结果中查找含有指定关键字所在的行;
* 如果关键字是空的,则获取命令得到的所有结果;
* 如果关键字不是空的,则将获取从该字符串开始到其所在行行尾的这部分的字符串
* 例:`ls -alh`之后,查找关键字tmp:
* `use_popen("ls -alh", "tmp");`
* 如果有带有”tmp“的文件或者文件夹只有一个:"tmp.txt",
* 则上面的函数的返回值是:"tmp.txt"。
* 注意:仅返回查找到的第一个tmp,说的不太明白,还是看代码吧。
****************************************************************
*/
string use_popen(const string& Linux_command, const string& key){
// 获取命令执行的结果
FILE *fp;
if ((fp = popen(Linux_command.c_str(), "r")) == NULL)
return "error1";
char buf[MAXLINE];
stringstream ss1;
while (fgets(buf, MAXLINE, fp) != NULL){
ss1 << string(buf); // 每一行之后都带有换行符\n
}
if (pclose(fp) == -1)
return "error2";
string cmd_ret = ss1.str(); // Linux command 命令成功执行之后的结果
// 获取执行结果中的关键字所在的行
if(key.empty()){ // 如果关键字是空的,则获取命令得到的所有结果
int end = cmd_ret.size()-1;
while(end>-1 && cmd_ret[end]=='\n'){
cmd_ret.pop_back(); // 去掉最后面的几个换行符\n
--end;
}
return cmd_ret;
}
stringstream ss2; // 如果关键字不是空的,则将获取从该字符串开始到其所在行行尾的这部分的字符串
int idx = cmd_ret.find(key); // 仅返回查找到的第一个tmp
if (idx != string::npos){
while(cmd_ret[idx] != '\n'){
ss2 << cmd_ret[idx];
++idx;
}
}else{
return "error3";
}
string keyline = ss2.str();
return keyline;
}