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

标签 c++ file debugging logging output

<分区>

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

#ifdef _DEBUG
     std::clog << "message etc" << std::endl;
#endif

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

最佳答案

您可以设置与使用文件保存数据的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;
}

关于c++ - 将源中的 std::clog 移动到输出文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34618916/

相关文章:

c++ - 函数返回的神秘段错误,不涉及指针或分配

c++ - 使用模板在 C++ 中映射函数

c++ - 成员变量默认初始化模板

c++ - boost::filesystem 如何将正确的文件路径读入 stringstream?

c# - 从 VB6 DLL 项目调试 C#.Net DLL 项目

c++ - 返回 std::stringstream - 编译失败

java - IOUtils.copy 是否会阻塞直到写入完成?

c# - 在 C# 中写入 linux tty (/dev/) 文件

debugging - 无需调试即可启动

javascript - 如何在我的 javascriptAPP 中从 C# 打开弹出消息?