正在将源代码中的std::clog移动到输出文件

Moving std::clog in source to output file

本文关键字:clog 移动 输出 文件 std 源代码      更新时间:2023-10-16

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

#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;
}

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

重定向的含义而言,它实际上在一定程度上取决于您的shell语法。根据这个参考,std::clog通常与std::cerr:结合

全局对象std::clogstd::wclog控制输出到实现定义类型的流缓冲区(从std::streambuf派生),该缓冲区与标准C输出流stderr相关联,但与std::cerr/std::wcerr不同,这些流不会自动刷新,也不会自动与cout绑定()。

例如,在bash中,你会做一些类似的事情

$ program 2> Logs.txt

关于以编程方式重定向,您可以按照R Sahu的回答中提到的或在当前标记的副本中解释的方式进行重定向。