在C/C++程序中执行终端命令并获取输出

在C/C++程序中执行命令并获取输出


在程序中执行终端命令并获取输出大概有两个思路:
1.在执行命令时将输出重定向到文件中,然后去读取文件获取命令行的输出,这样做的好处就是可以保留命令行输出到文件中,可以通过查看文件看到命令行输出的结果。
2.可以通过popen函数直接获取执行命令的结果,这样做没有中间产物不用读写文件代码量少清晰,如果是常规的项目需要这么做防止中间产物泄露。
下面直接上代码:
1.使用system重定向到文件中去:

#include <QApplication>
#include <iostream>
#include <fstream>
#include <string>

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
void ReadFile(const std::string &file_name)
{
    std::ifstream fp(file_name);
    if(!fp.is_open())
    {
        std::cout<<"open error"<<std::endl;
    }
    std::string read_str;
    while(std::getline(fp,read_str))
    {
        std::cout<<"ReadFile:   "<<read_str<<std::endl;
    }
    fp.close();
}

int main(int argc, char *argv[])
{
    std::system("ls>1.txt");
    ReadFile("1.txt");
    return 0;
}



输出:
ReadFile:   1.txt
ReadFile:   main.o
ReadFile:   mainwindow.o
ReadFile:   Makefile
ReadFile:   moc_mainwindow.cpp
ReadFile:   moc_mainwindow.o
ReadFile:   moc_predefs.h
ReadFile:   ui_mainwindow.h
ReadFile:   untitled

2.使用popen:

#include <QApplication>
#include <iostream>
#include <fstream>
#include <string>

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
void GetCommdResult(const std::string &cmd)
{
    FILE *fp=nullptr;
    if((fp=popen(cmd.c_str(),"r"))==nullptr)
    {
        return;
    }
    char read_str[512]="";
    while(fgets(read_str,sizeof(read_str),fp))
    {
        std::cout<<"GetCommdResult:   "<<read_str<<std::endl;
    }
    pclose(fp);
}

int main(int argc, char *argv[])
{
    std::string cmd("ls");
    GetCommdResult(cmd);
    return 0;
}



输出:
GetCommdResult:   1.txt

GetCommdResult:   main.o

GetCommdResult:   mainwindow.o

GetCommdResult:   Makefile

GetCommdResult:   moc_mainwindow.cpp

GetCommdResult:   moc_mainwindow.o

GetCommdResult:   moc_predefs.h

GetCommdResult:   ui_mainwindow.h

GetCommdResult:   untitled

这里我使用的是QT编写的代码,执行完发现使用popen获取到的字符串会多一个回车或者是换行符,这里我没有去细究,大家感兴趣可以去研究一下。如果工作中我们遇到处理字符串的时候都会将一些特殊字符删除。

  • 2
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值