【问题标题】:How to redirect stdout and stderr streams (Multiplatform)?如何重定向标准输出和标准错误流(多平台)?
【发布时间】:2011-12-25 23:37:21
【问题描述】:

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

PS:对不起,我的英语不好......

【问题讨论】:

标签: c++ console-application stdout stderr multiplatform


【解决方案1】:

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

  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()。您可能希望使用管道而不仅仅是另一个文件,并且您需要非常小心阻塞(因此可能需要一个专用线程)

【讨论】:

    猜你喜欢
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    • 2012-03-30
    • 2020-11-05
    • 2010-09-21
    • 1970-01-01
    • 2011-10-11
    • 2014-03-22
    相关资源
    最近更新 更多