我正在编写使用外部库的 GL 应用程序,它将错误打印到控制台。我想捕获它并在游戏控制台中打印。
PS:抱歉,我的英语不好......
最佳答案
您可以采取两种基本方法:
如果库都使用
std::cout
对于您想要捕获的 IO,您可以 write your ownbasic_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; }
您可以使用特定于平台的方法,例如在 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/