如何重定向stdout和stderr流(多平台)? [英] How to redirect stdout and stderr streams (Multiplatform)?
问题描述
我正在编写使用外部库的GL应用程序,它会向控制台打印错误。
PS:对不起,我的英语不好....
- 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;
}
-
在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:
If the libraries all use
std::cout
for the IO you want to capture you can write your ownbasic_streambuf
. You can then just callstd::cout.rdbuf(mybufinst);
to replace the streambuffer, for example using thestd::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; }
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 withSetStdHandle()
. 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屋!