C++ std::ofstream是否保证在打开新文件时关闭旧打开的文件? #包括 int main() { auto fout=std::of流(“/tmp/a.txt”); fout.open(“/tmp/b.txt”);//会关闭“/tmp/a.txt”吗? fout.open(“/tmp/c.txt”);//会关闭“/tmp/b.txt”吗? }
打开新文件时,std::of Stream是否保证关闭旧打开的文件?第二次调用和后续调用将失败 [filebuf.members]C++ std::ofstream是否保证在打开新文件时关闭旧打开的文件? #包括 int main() { auto fout=std::of流(“/tmp/a.txt”); fout.open(“/tmp/b.txt”);//会关闭“/tmp/a.txt”吗? fout.open(“/tmp/c.txt”);//会关闭“/tmp/b.txt”吗? },c++,c++11,standards,file-handling,iostream,C++,C++11,Standards,File Handling,Iostream,打开新文件时,std::of Stream是否保证关闭旧打开的文件?第二次调用和后续调用将失败 [filebuf.members] basic_filebuf*open(const char*s,ios_base::openmode模式) 2效果:如果打开()!=false,返回空指针。否则 [ofstream.members] void open(const char*s,ios_base::openmode=ios_base::out) 3种效果:调用rdbuf()->open(s,mode
basic_filebuf*open(const char*s,ios_base::openmode模式)代码>
2效果:如果打开()!=false,返回空指针。否则
[ofstream.members]
void open(const char*s,ios_base::openmode=ios_base::out)代码>
3种效果:调用rdbuf()->open(s,mode | ios_base::out)
。如果该函数不返回空指针,则调用clear()
,否则调用setstate(failbit)
我没有看到任何明确的行为规范ofstream::open
本质上是将open
调用传递到原始设备缓冲区。对于这一点,没有具体说明如果已打开另一个文件会发生什么,也没有具体说明如果打开一个文件但打开失败会发生什么。但是,您至少应该预料到,如果在该对象上打开了一个新文件,旧文件将被关闭,因为设备缓冲区负责管理单个资源,不会泄漏资源。只是想把这个消息放在这里,因为您删除了另一个Q。在C++20中,比较得到了重大更新,其中之一是操作符==
应该向前和向后工作。这意味着,如果希望LHS和RH是不同的类型,则不需要再编写两个重载。
#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?
}