[英]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.