如何使用 POSIX 在 C++ 中执行命令并获取命令的输出? [英] How do I execute a command and get the output of the command within C++ using POSIX?

查看:47
本文介绍了如何使用 POSIX 在 C++ 中执行命令并获取命令的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种在 C++ 程序中运行时获取命令输出的方法.我已经看过使用 system() 函数,但这只会执行一个命令.这是我正在寻找的示例:

I am looking for a way to get the output of a command when it is run from within a C++ program. I have looked at using the system() function, but that will just execute a command. Here's an example of what I'm looking for:

std::string result = system("./some_command");

我需要运行任意命令并获取其输出.我查看了 boost.org,但没有找到任何可以满足我需求的内容.

I need to run an arbitrary command and get its output. I've looked at boost.org, but I have not found anything that will give me what I need.

推荐答案

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

std::string exec(const char* cmd) {
    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();
    }
    return result;
}

C++11 之前的版本:

Pre-C++11 version:

#include <iostream>
#include <stdexcept>
#include <stdio.h>
#include <string>

std::string exec(const char* cmd) {
    char buffer[128];
    std::string result = "";
    FILE* pipe = popen(cmd, "r");
    if (!pipe) throw std::runtime_error("popen() failed!");
    try {
        while (fgets(buffer, sizeof buffer, pipe) != NULL) {
            result += buffer;
        }
    } catch (...) {
        pclose(pipe);
        throw;
    }
    pclose(pipe);
    return result;
}

_popen_pclose 替换 popenpclose for Windows.

Replace popen and pclose with _popen and _pclose for Windows.

这篇关于如何使用 POSIX 在 C++ 中执行命令并获取命令的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆