【问题标题】:Moving std::clog in source to output file [duplicate]将源中的 std::clog 移动到输出文件
【发布时间】:2016-04-09 16:54:39
【问题描述】:

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

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

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

【问题讨论】:

  • 你不能,也不能不重定向正常输出(如果你从程序外部使用重定向)。唯一的方法是使用另一个输出流,可能是您初始化到输出文件流或std::clog 的引用。

标签: c++ file debugging logging output


【解决方案1】:

您可以设置与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;
}

【讨论】:

【解决方案2】:

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

至于 redirect 意味着从程序代码之外,它实际上取决于你的 shell 语法。根据this referencestd::clog通常绑定到std::cerr

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

例如在 bash 中,你会做类似

$ program 2> Logs.txt

关于以编程方式重定向,您可以按照R Sahu's answer 中的说明或currently marked duplicate 中的说明进行操作。

【讨论】:

    猜你喜欢
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-18
    • 1970-01-01
    • 2012-10-07
    相关资源
    最近更新 更多