Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/127.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
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 - Fatal编程技术网

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++ 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

打开新文件时,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 | 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?
}