gpt4 book ai didi

c++ - 如何使用 POSIX 在 C++ 中执行命令并获取命令的输出?

转载 作者:太空宇宙 更新时间:2023-11-04 11:52:25 24 4
gpt4 key购买 nike

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

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

我需要运行任意命令并获取其输出。我看过 boost.org ,但我还没有找到任何可以满足我需要的东西。

最佳答案

#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 之前的版本:

#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;
}

popenpclose 替换为 _popen_pclose for Windows。

关于c++ - 如何使用 POSIX 在 C++ 中执行命令并获取命令的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55642906/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com