应用程序崩溃时如何处理流对象

问题描述 投票:0回答:2

我有一个单例记录器类,它将用于将数据写入单个文件,我只是想知道在应用程序崩溃的情况下如何处理

ofstream
对象。

#ifndef LOG_ERROR_H_
#define LOG_ERROR_H_

#include <iostream>
#include <thread>
#include <mutex>
#include <string>
#include <fstream>
#include <memory>

namespace batch
{

  class ErrorLogger
  {

  public:
    ErrorLogger(const ErrorLogger &) = delete; 

    static ErrorLogger& Instance(std::string filename_)
    {
      static ErrorLogger error_instance(filename_);
      return error_instance;
    }
    

    void WriteLine(std::string content)
    {
      try
      {
        std::lock_guard<std::mutex> lk(error_stream_mutex);
        error_stream << content << std::endl;
      }
      catch(std::runtime_error const& e)
      {
        //cout
      }
    }

    ~ErrorLogger()
    {
      error_stream.close(); //Destructor is not getting called, should I explicitly call it?
    }

  private:
    std::ofstream error_stream;
    std::mutex error_stream_mutex;

    ErrorLogger(std::string filename) 
    {
        error_stream.open(filename);

        if (error_stream.fail())
        {
          throw std::iostream::failure("Cannot open file: " + filename);
        }
    }
  };
}

#endif

我尝试的不是始终保持

ofstream
对象打开,实例化一次然后
open
close
在写作期间但让我们假设一个场景,我得到实例并且
ofstream
对象被初始化并在调用之前
WriteLine
(),应用程序崩溃了那么我应该如何处理
ofstream
对象呢?

ErrorLogger(std::string filename) 
{
    error_stream(filename);
    if (error_stream.fail())
    {
        throw std::iostream::failure("Cannot open file: " + filename);
    }
}
void WriteLine(std::string content)
{
    try
    {
    error_stream.open(filename);
    if (error_stream.fail())
    {
        throw std::iostream::failure("Cannot open file: " + filename);
    }
    std::lock_guard<std::mutex> lk(error_stream_mutex);
    error_stream << content << std::endl;
    error_stream.close();
    }
    catch(std::runtime_error const& e)
    {
    //cout
    }
}    

所以问题是如何正确处理 error_stream(在积极的情况下以及应用程序崩溃的情况下),即我应该什么时候关闭它,现在它没有关闭。

c++ singleton file-handling ofstream
2个回答
3
投票

如果应用程序崩溃,操作系统将关闭所有打开的文件,因此您无需对该场景进行任何操作。 (更不用说你真的什么也做不了。)

虽然应用程序尚未崩溃(但),您可以使用

std::ostream::flush
继续刷新文件(请参阅 https://cplusplus.com/reference/ostream/ostream/flush/)而不是关闭它然后重新打开它;它一定会表现得更好。


-1
投票

我不知道您的其余代码是什么样子,但也许这对您的情况有所帮助:Singleton Destructors

© www.soinside.com 2019 - 2024. All rights reserved.