简体   繁体   English

使用 C++ 执行命令并捕获 output 和状态

[英]Execute a command with C++ and capture the output and the status

How can I execute a system command with C++ and capture its output and the status.如何使用 C++ 执行系统命令并捕获其 output 和状态。 It should look something like this:它应该看起来像这样:

Response launch(std::string command);

int main()
{
    auto response = launch("pkg-config --cflags spdlog");
    std::cout << "status: " << response.get_status() << '\n'; // -> "status: 0"
    std::cout << "output: " << response.get_output() << '\n'; // -> "output: -DSPDLOG_SHARED_LIB -DSPDLOG_COMPILED_LIB -DSPDLOG_FMT_EXTERNAL"
}

Using std::system you can only get status.使用std::system你只能获得状态。 I also tried this solution but it only captures the output and it seems to be very "hacky" and not safe.我也尝试了这个解决方案,但它只捕获 output 并且它似乎非常“hacky”并且不安全。 There must be a better way to do it but I haven't found one yet.必须有更好的方法来做到这一点,但我还没有找到。 If there isn't a simple and portable solution, I would also use a library.如果没有简单且可移植的解决方案,我也会使用库。

I found a way with redirecting the output to a file and reading from it:我找到了一种将 output 重定向到文件并从中读取的方法:

#include <string>
#include <fstream>
#include <filesystem>

struct response
{
    int status = -1;
    std::string output;
};

response launch(std::string command)
{
    // set up file redirection
    std::filesystem::path redirection = std::filesystem::absolute(".output.temp");
    command.append(" &> \"" + redirection.string() + "\"");

    // execute command
    auto status = std::system(command.c_str());

    // read redirection file and remove the file
    std::ifstream output_file(redirection);
    std::string output((std::istreambuf_iterator<char>(output_file)), std::istreambuf_iterator<char>());
    std::filesystem::remove(redirection);

    return response{status, output};
}

Still seems a bit "hacky" but it works.仍然看起来有点“hacky”,但它确实有效。 I would love to see a better way without creating and removing files.我很想看到一种更好的方法,而无需创建和删除文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM