有时候,我们需要在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