【问题标题】:Does std::ofstream guarantee the old open file will be closed if opening new one?std::ofstream 是否保证在打开新文件时将关闭旧打开的文件?
【发布时间】:2021-05-10 04:12:15
【问题描述】:
#include <fstream>

int main()
{
    auto fout = std::ofstream("/tmp/a.txt");
    fout.open("/tmp/b.txt"); // Will "/tmp/a.txt" be closed?
    fout.open("/tmp/c.txt"); // Will "/tmp/b.txt" be closed?
}

是否std::ofstream保证打开新文件会关闭旧打开的文件?

【问题讨论】:

  • 我没有看到任何明确的行为规范。 ofstream::open 本质上将open 调用传递到其原始设备缓冲区。 documentation 并没有具体说明如果 不同的 文件已经打开会发生什么,也没有具体说明如果您打开文件并且打开​​失败会发生什么。但是,您至少应该期望如果在该对象上打开一个新文件,旧文件关闭,因为设备缓冲区负责管理单个资源并且不会泄露资源。
  • 只是想把这个听到,因为你删除了你的另一个 Q。在 C++20 中,比较有一个重大更新,其中一个是 operator == 应该向前和向后工作。这意味着当您希望 LHS 和 RHS 为不同类型时,您不再需要编写两个重载。

标签: c++ c++11 standards file-handling iostream


【解决方案1】:

第二次及以后的调用将失败。

[filebuf.members]
basic_filebuf* open(const char* s, ios_base::openmode mode);
2 效果:如果is_open() != false,返回一个空指针。否则……

[ofstream.members]
void open(const char* s, ios_base::openmode mode = ios_base::out);
3 效果:调用rdbuf()-&gt;open(s, mode | ios_base::out)。如果该函数不返回空指针调用clear(),否则调用setstate(failbit)

【讨论】:

    猜你喜欢
    • 2011-01-13
    • 1970-01-01
    • 1970-01-01
    • 2017-04-10
    • 1970-01-01
    • 2012-10-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    相关资源
    最近更新 更多