C++ 执行终端命令,并且返回执行命令的结果

有时候,我们需要在C++代码里面执行一些终端命令,然后获取返回值,对返回的结果进行操作,十分的方便。
下面给出C++代码:



#include <cstdio>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <array>

std::string getLastestGitInfo() {
    const char* cmd = "git log < /dev/null 2>&1 | grep "Date:" | head -n1";  //git log < /dev/null 2>&1 | grep "Date:" | head -n1
    std::array<char, 128> buffer;
    std::string result;
    std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose);
    if (!pipe) {
        throw std::runtime_error("popen() failed!");
    }
    while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
        result += buffer.data();
    }
    if(!result.empty())
        return result.substr(0, 33) ;
    else
        return "vslam";
}
 
int main()
{
    char * cmd = "git log | grep \"Date:\" | head -n1";
    std::string result=getLastestGitInfo();
    std::cout<<result;
    
    return 0;
}

上面的代码是获取当前项目git的提交日期,十分的方便。

参考链接:
https://stackoverflow.com/questions/478898/how-do-i-execute-a-command-and-get-the-output-of-the-command-within-c-using-po

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值