c++ - 如何重定向 stdout 和 stderr 流(多平台)?

标签 c++ console-application stdout stderr multiplatform

我正在编写使用外部库的 GL 应用程序,它将错误打印到控制台。我想捕获它并在游戏控制台中打印。

PS:抱歉,我的英语不好......

最佳答案

您可以采取两种基本方法:

  1. 如果库都使用 std::cout对于您想要捕获的 IO,您可以 write your own basic_streambuf 。然后您可以调用std::cout.rdbuf(mybufinst);替换流缓冲区,例如使用 std::basic_stringbuf :

    #include <sstream>
    #include <iostream>
    
    int main() {
       static std::basic_stringbuf<std::ostream::char_type> buf;
       std::cout.rdbuf(&buf);
       std::cout << "Hello captured world!\n";
       std::cerr << "Stole: " << buf.str() << std::endl;
    }
    
  2. 您可以使用特定于平台的方法,例如在 POSIX 系统上 dup2() will allow you to replace a file descriptor with another one ,或在 Windows 上使用 SetStdHandle() 。您可能希望使用管道而不仅仅是另一个文件,并且您需要非常小心阻塞(因此可能需要专用线程)

关于c++ - 如何重定向 stdout 和 stderr 流(多平台)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8076830/

相关文章:

c++ - 使用 MFC 在 opencv 中的函数 cvInitImageHeader 中输入 roi 错误

c - stdio 函数(sprintf、vsprintf 和 fprintf)背后的命名约定是什么?

c++ - 如果使用 vector 作为容器,如何弹出队列

c++ - 使用 GSL 拟合分段 "broken stick"模型

C# 控制台应用程序 - OO 数学/思维问题

C#:糟糕的类设计(第一个 OOP)

c# - asp.net core 2.1 ConfigurationBuilder GetSection 函数返回null

c - 如何检查标准输出是否已在 Windows 上重定向到 NUL(在 Linux 上也称为/dev/null)?

c - 如何将 stdout 重定向到 COM 端口

python - Kdevelop 与 Python/C++ : no output in debug mode