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

新手上路,请多包涵

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

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

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

原文由 Misha M 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1k
2 个回答
#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

原文由 waqas 发布,翻译遵循 CC BY-SA 4.0 许可协议

请注意,您可以通过将输出重定向到文件然后读取它来获取输出

它显示在 std::system 的文档中

您可以通过调用 WEXITSTATUS 宏来接收退出代码。

     int status = std::system("ls -l >test.txt"); // execute the UNIX command "ls -l >test.txt"
    std::cout << std::ifstream("test.txt").rdbuf();
    std::cout << "Exit code: " << WEXITSTATUS(status) << std::endl;

原文由 Pikacz 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题