簡體   English   中英

使用 C++ 執行命令並捕獲 output 和狀態

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

如何使用 C++ 執行系統命令並捕獲其 output 和狀態。 它應該看起來像這樣:

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"
}

使用std::system你只能獲得狀態。 我也嘗試了這個解決方案,但它只捕獲 output 並且它似乎非常“hacky”並且不安全。 必須有更好的方法來做到這一點,但我還沒有找到。 如果沒有簡單且可移植的解決方案,我也會使用庫。

我找到了一種將 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};
}

仍然看起來有點“hacky”,但它確實有效。 我很想看到一種更好的方法,而無需創建和刪除文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM