如何重定向stdout和stderr流(多平台)? [英] How to redirect stdout and stderr streams (Multiplatform)?

查看:296
本文介绍了如何重定向stdout和stderr流(多平台)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写使用外部库的GL应用程序,它会向控制台打印错误。



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




  1. p>如果库所有使用 std :: cout 用于要捕获的IO,您可以编写您自己的 basic_streambuf 。然后你可以调用 std :: cout.rdbuf(mybufinst); 来替换streambuffer,例如使用 std :: basic_stringbuf

      #include< sstream& 
    #include< iostream>

    int main(){
    static std :: basic_stringbuf< std :: ostream :: char_type> f
    std :: cout.rdbuf(& buf);
    std :: cout<< Hello captured world!\\\
    ;
    std :: cerr<< Stole:< buf.str()<< std :: endl;
    }


  2. 在POSIX系统上 dup2()将允许您用另一个替换文件描述符,或在Windows上使用 SetStdHandle() 。你可能想使用管道,而不是只使用另一个文件,你需要对阻塞非常小心(因此可能需要一个专用线程)



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....

解决方案

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)

这篇关于如何重定向stdout和stderr流(多平台)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆