c++ - popen() 将执行命令的输出写入 cout

标签 c++ file popen

我正在编写一个需要打开另一个进程并获取其输出的应用程序。我在网上看到的所有地方都说我必须使用 popen 并从文件中读取。

但我无法读取它。命令的输出被输出到调用应用程序的控制台窗口中。下面是我正在使用的代码。我添加了一些打印以进行调试。

#include <string>
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <array>

int main()
{
    // some command that fails to execute properly.
    std::string command("ls afskfksakfafkas");

    std::array<char, 128> buffer;
    std::string result;

    std::cout << "Opening reading pipe" << std::endl;
    FILE* pipe = popen(command.c_str(), "r");
    if (!pipe)
    {
        std::cerr << "Couldn't start command." << std::endl;
        return 0;
    }
    while (fgets(buffer.data(), 128, pipe) != NULL) {
        std::cout << "Reading..." << std::endl;
        result += buffer.data();
    }
    auto returnCode = pclose(pipe);

    std::cout << result << std::endl;
    std::cout << returnCode << std::endl;

    return 0;
}

读数实际上从未打印到我的 cout 中,结果是一个空字符串。我在终端中清楚地看到命令的输出。如果命令正常退出,则行为符合预期。但我只捕获错误情况的输出。

最佳答案

Popen 不捕获 stderr,只捕获 stdout。将 stderr 重定向到 stdout 可以解决这个问题。

#include <string>
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <array>

int main()
{
    std::string command("ls afskfksakfafkas 2>&1");

    std::array<char, 128> buffer;
    std::string result;

    std::cout << "Opening reading pipe" << std::endl;
    FILE* pipe = popen(command.c_str(), "r");
    if (!pipe)
    {
        std::cerr << "Couldn't start command." << std::endl;
        return 0;
    }
    while (fgets(buffer.data(), 128, pipe) != NULL) {
        std::cout << "Reading..." << std::endl;
        result += buffer.data();
    }
    auto returnCode = pclose(pipe);

    std::cout << result << std::endl;
    std::cout << returnCode << std::endl;

    return 0;
}

关于c++ - popen() 将执行命令的输出写入 cout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44610978/

相关文章:

java - 在 Java 中是否有 try/catch 的替代方法来打开文件?

c++ - 使用 Poco 和 Boost C++ 的多个 Http 服务器

java读取并写入\u05DC为 '?'

c - 使用 "scanf()"的返回值来检查文件结尾

java - equals()方法未从文件中检测到单词

c++ - 如何确保 popen()ed 进程在退出时运行析构函数?

Python - 使用许多参数调用 popen

c++ - Qt:在 QScrollArea 中显示图像(QLabel)

c++ - size_t vs int 警告

linux - popen ("tar xvf tarball.tar") 在调试中工作但在发布版本中不工作