c++ - std::ofstream 是否保证打开新文件时将关闭旧的打开文件?

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

#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 是否保证打开新文件时关闭旧文件?

最佳答案

第二次及后续调用将失败。

[filebuf.members]
basic_filebuf* open(const char* s, ios_base::openmode mode);
2 Effects: If is_open() != false, returns a null pointer. Otherwise...

[ofstream.members]
void open(const char* s, ios_base::openmode mode = ios_base::out);
3 Effects: Calls rdbuf()->open(s, mode | ios_base::out). If that function does not return a null pointer calls clear(), otherwise calls setstate(failbit)

关于c++ - std::ofstream 是否保证打开新文件时将关闭旧的打开文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67464690/

相关文章:

xml - 将 JSON 转换为 XML 并返回是否有严格的规则?

c++ - TCHAR 数组在反斜杠后追加 w

c++ - 将 lambda 传递给函数模板

c++ - 在 C++ 中,以这种方式包括有问题吗?

c++ - RapidXML 提供空 CDATA 节点

c++ - 在 MacOSX Lion 上编译 gcc 4.6.1 C++0x 线程代码时出错

c++ - 内联命名空间变量是否具有内部链接?如果不是,为什么下面的代码有效?

Java-在不同类中的两个变量之间创建一致性

java - 字符串池优化是Java定义的吗?

C++使变量类型取决于用户输入