更改或检查std :: ofstream的openmode [英] Change or check the openmode of a std::ofstream

查看:359
本文介绍了更改或检查std :: ofstream的openmode的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一些使用std::ofstream执行大量文件I/O的代码中,我在缓存流以提高效率.但是,有时我需要更改文件的打开模式(例如,append vs truncate).这是一些类似的模拟代码:

In some code that does a lot of file i/o using std::ofstream, I'm caching the stream for efficiency. However, sometimes I need to change the openmode of the file (e.g. append vs truncate). Here is some similar mock code:

class Logger {
public:
    void write(const std::string& str, std::ios_base::openmode mode) {
        if (!myStream.is_open) myStream.open(path.c_str(), mode);
        /* Want: if (myStream.mode != mode) {
                     myStream.close();
                     myStream.open(path.c_str(), mode);
                 }
        */
        myStream << str;
     }
private:
    std::ofstream myStream;
    std::string path = "/foo/bar/baz";
}

有人知道吗?

  • 有一种方法可以更改ofstream的打开模式吗?
  • 如果没有,是否有办法找出ofstream当前的openmode是什么,以便我仅在必要时关闭并重新打开它?
  • There is a way to change the openmode of the ofstream?
  • If not, is there a way to find out what the current openmode of an ofstream is so I can close and reopen it only when necessary?

推荐答案

@Ari由于默认实现不允许您执行任何操作,因此您可能必须封装ofstream并提供其他get/set开放模式功能,其中您的新对象将模拟所需的行为.

@Ari Since the default implementation doesn't allow what you want todo, you might have to encapsulate ofstream and provide the additional get/set open mode functionality in which your new object would simulate the desired behavior.

也许是这样

class FileOutput{
  private:
    ostream& streamOut;
    std::ios_base::openmode currentOpemMode;
  public:
    FileOutput(ostream& out, std::ios_base::openmode mode)
     : streamOut(out), currentOpemMode(mode){}

    void setOpenMode(const std::ios_base::openmode newOpenMode){
          if(newOpenMode != currentOpemMode){
              currentOpemMode = newOpenMode;
              updateUsedMode();
          }
    }
  private:
    void updateUsedMode(){
          if(currentOpemMode == ios_base::app){  /* use seekg/tellg to move pointer to end of file */}
          else if(currentOpenMode == binary){ /* close stream and reopen in binary mode*/}
         //...and so on
};

这篇关于更改或检查std :: ofstream的openmode的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆