首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >正在将源文件中的std::clog移动到输出文件

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

Stack Overflow用户
提问于 2016-01-06 02:36:33
回答 2查看 4.3K关注 0票数 2

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

代码语言:javascript
复制
#ifdef _DEBUG
     std::clog << "message etc" << std::endl;
#endif

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

EN

回答 2

Stack Overflow用户

发布于 2016-01-06 02:43:39

您可以设置与clog关联的缓冲区,该缓冲区使用要将其数据保存到的文件。

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

代码语言:javascript
复制
#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;
}
票数 5
EN

Stack Overflow用户

发布于 2016-01-06 02:45:15

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

由于远重定向是指程序代码之外的重定向,实际上这有点取决于您的shell语法。根据this reference的说法,std::clog通常绑定到std::cerr

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

例如,在bash中,你可以这样做

代码语言:javascript
复制
$ program 2> Logs.txt

关于以编程方式重定向,您可以按照R Sahu's answer中提到的或currently marked duplicate中解释的那样进行。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34618916

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档