How to redirect stdout and stderr streams (Multiplatform)?

旧城冷巷雨未停 提交于 2019-12-02 04:15:39

问题


I'm writing GL application that uses external libs, which print errors to the console. I want to catch that and print in the in-game console.

PS: Sorry, for my bad english....


回答1:


There are two basic approaches you could take to this:

  1. If the libraries all use std::cout for the IO you want to capture you can write your own basic_streambuf. You can then just call std::cout.rdbuf(mybufinst); to replace the streambuffer, for example using the 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. You can use a platform specific approach, e.g. on POSIX systems dup2() will allow you to replace a file descriptor with another one, or on Windows with SetStdHandle(). You'd want to use pipes rather than just another file probably and you'd need to be really careful about blocking (so probably want a dedicated thread)



来源:https://stackoverflow.com/questions/8076830/how-to-redirect-stdout-and-stderr-streams-multiplatform

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!