【问题标题】:Change or check the openmode of a std::ofstream更改或检查 std::ofstream 的打开模式
【发布时间】:2012-11-21 16:34:57
【问题描述】:

在一些使用 std::ofstream 执行大量文件 i/o 的代码中,我正在缓存流以提高效率。但是,有时我需要更改文件的打开模式(例如追加与截断)。下面是一些类似的模拟代码:

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 是什么,以便我可以仅在必要时关闭并重新打开它?

【问题讨论】:

  • 您可能想了解these 状态函数,这些函数允许您设置或返回标志的状态.....
  • 我只是好奇你为什么要改变它?什么时候适用这样的条件?
  • @noleptr 我看过这些,但它们不允许您更改文件的打开模式。您只能获取/设置goodbitbadbitfailbiteofbit。 @BartekBanachewicz 我正在重做部分库的实现。我也不确定在什么情况下你实际上需要这个,但我需要保持与以前相同的行为。以前,这是通过特定于平台的系统调用来完成的,这些系统调用可以让您查询文件的状态。
  • 您可能必须根据要设置的标志手动设置流指针
  • @user814628 你能详细说明一下吗?

标签: c++ iostream ofstream c++03


【解决方案1】:

@Ari 由于默认实现不允许您做您想做的事情,您可能必须封装 ofstream 并提供额外的 get/set 开放模式功能,您的新对象将在其中模拟所需的行为。

也许是这样的

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
};

【讨论】:

    猜你喜欢
    • 2015-05-14
    • 1970-01-01
    • 2010-10-23
    • 2010-09-26
    • 2018-04-11
    • 1970-01-01
    • 2012-10-12
    • 1970-01-01
    • 2011-05-18
    相关资源
    最近更新 更多