gpt4 book ai didi

c++ - 应用程序崩溃时如何刷新ostream

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:54:54 24 4
gpt4 key购买 nike

我有一个基于 ostream 的子类,它捕获我程序的调试消息。

/** @brief Customized output stream with "tee" feature */
template <typename CharT, typename Traits = std::char_traits<CharT> >
class basic_tostream : public std::basic_ostream<CharT, Traits> {
public:
basic_tostream(std::basic_ostream<CharT, Traits> & o1, /**< main ostream */
std::basic_ostream<CharT, Traits> & o2 /**< teed ostream */)
: std::basic_ostream<CharT, Traits>(&tbuf), tbuf(o1.rdbuf(), o2.rdbuf())
{ /* empty */ }

private:
tee_outbuf<CharT, Traits> tbuf;
}; // end_class: basic_tostream

我如何使用这个类:

std::ofstream debugFile("debug.txt")
tostream tout(std::cout, debugFile);
/* computation */
tout << "message\n";
/* other computation */

问题: 当应用程序正常退出时,该类工作正常。但是在崩溃的情况下(例如数组索引超出范围等),'tout' 会打印出所有消息到控制台,但 'debugFile' 不会捕获所有打印输出。

问题:那么,当应用程序崩溃时,如何正确刷新 ostream 缓冲区到输出文件?

最佳答案

一种方法是使用崩溃处理程序。在 Windows 中,它以 dbghlp.dll 和即时调试子系统的形式出现。

但到目前为止,最简单的方法是以两种方式之一刷新每条消息:

  1. 保持文件打开,并在每条消息后调用 flush
  2. 以附加模式打开文件,写入,并在每次写入消息时关闭文件。

我相信使用 endl 而不是 "\n" 会隐式刷新。

关于c++ - 应用程序崩溃时如何刷新ostream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16579467/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com