我认为这是一个很好的做法,关闭你的流,因为你需要冲洗的缓冲,这是我一直告诉

To append to Amy Lee's answer, it's better to do it manually because this way you can check for errors too.

顺便说一句,根据 “关闭”手册:

未检查 Close ()是一种常见的,但是 严重的编程错误 可能在以前的错误 首先报告写(2)操作 在最后关闭()。没有检查 关闭文件时返回值可能 导致无声的数据丢失。这可以 特别是在使用 NFS 和 磁盘配额。

A successful close does not guarantee 数据已经成功 saved to disk, as the kernel defers 写。这是不常见的 时刷新缓冲区 小溪已经关闭了,如果你需要的话 确保数据是物理上的 存储使用 fsync (2) 在磁盘硬件上。)

我认为以前的答案是误导性的。

fstream a proper RAII object, it 是的 close automatically at the end of the scope, and there is absolutely no need whatsoever to call close manually when closing at the end of the scope is sufficient.

In particular, it’s not a “best practice” and it’s not necessary to flush the output.

虽然 Drakosha 是对的,调用 close可以让您检查流的故障位,但是没有人这样做。

在理想情况下,只需事先调用 stream.exceptions(ios::failbit)并处理在 fstream的析构函数中抛出的异常。但不幸的是,析构函数中的异常在 C + + 中是一个破碎的概念,所以这不是一个好主意。

因此,如果你想检查关闭文件是否成功,可以手动执行(但仅限于此时)。