将源中的 std::clog 移动到输出文件

Jam*_*ing 2 c++ debugging logging file output

我的代码中有一条基本的调试消息,用于打印有关调用什么函数的消息。

#ifdef _DEBUG
     std::clog << "message etc" << std::endl;
#endif
Run Code Online (Sandbox Code Playgroud)

如何重定向输出以将消息发送到文本文件?

R S*_*ahu 5

您可以设置与clog使用文件相关联的缓冲区来保存其数据。

这是一个演示该概念的简单程序。

#include <iostream>
#include <fstream>

int main()
{
   std::ofstream out("test.txt");

   // Get the rdbuf of clog.
   // We need it to reset the value before exiting.
   auto old_rdbuf = std::clog.rdbuf();

   // Set the rdbuf of clog.
   std::clog.rdbuf(out.rdbuf());

   // Write to clog.
   // The output should go to test.txt.
   std::clog << "Test, Test, Test.\n";

   // Reset the rdbuf of clog.
   std::clog.rdbuf(old_rdbuf);

   return 0;
}
Run Code Online (Sandbox Code Playgroud)