问题描述
我正在编写单元测试,因此无法更改我正在测试的文件中的代码.我正在测试的代码在 cout 中有消息,我试图将这些消息重定向到文件中以检查以确保程序输出正确的消息.有没有人有办法在另一个不会导致延迟的程序中重定向标准输出?我试过 freopen() 并且由于某种原因导致我的程序挂起.
I'm writing a unit test and therefore, cannot change the code within the file that I'm testing. The code that I'm testing has messages in cout that I am trying to redirect into a file to check to make sure that the program is outputting the right messages. Does anyone have a way to redirect stdout in another program that won't cause a lag? I have tried freopen() and that causes my program to hang for some reason.
推荐答案
您可以创建一个 filebuf
然后用它替换 cout
的 streambuf:
You could create a filebuf
then replace cout
's streambuf with it:
{
std::filebuf f;
f.open("output.txt", std::ios::out);
std::streambuf* o = std::cout.rdbuf(&f);
std::cout << "hello" << std::endl; // endl will flush the stream
std::cout.rdbuf(o);
}
您需要再次恢复cout
的原始streambuf(或将其设置为空指针),否则在刷新和销毁全局流时可能会崩溃,因为filebuf
将已经超出范围.
You need to restore cout
's original streambuf again (or set it to a null pointer) or it will probably crash when the global streams are flushed and destroyed, because the filebuf
will already have gone out of scope.
这篇关于从 C++ 中的另一个程序重定向标准输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!