Linux编程使用popen函数

18 篇文章 3 订阅

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;
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值