我需要关闭 std::fstream 吗?
可能的重复:
我需要手动关闭 ifstream 吗?
我需要调用 fstream.close() 或 fstream 是一个在销毁时关闭流的正确 RAII 对象吗?
我在方法中有一个本地 std::ofstream
对象。我可以假设退出此方法后文件始终关闭而不调用 close 吗?我找不到析构函数的文档。
Possible Duplicate:
Do I need to manually close a ifstream?
Do I need to call fstream.close()
or is fstream
a proper RAII object that closes the stream on destruction?
I have a local std::ofstream
object inside a method. Can I assume that the file is always closed after exiting this method without calling close? I could not find documentation of the destructor.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为关闭 fstream 是一个很好的做法,因为您需要刷新缓冲区,这是我被告知的
I think it's a good practice to close your fstream, cause you need to flush the buffer, that what i've been told
要附加到艾米·李的答案,最好手动执行,因为这样您也可以检查错误。
顺便说一句,根据 "close" 手册页:
To append to Amy Lee's answer, it's better to do it manually because this way you can check for errors too.
BTW, according to "close" manpage:
我认为之前的答案有误导性。
fstream
是一个正确的 RAII 对象,它确实在作用域结束时自动关闭,并且绝对没有任何必要< /em> 在范围末尾关闭时手动调用close
就足够了。特别是,这不是“最佳实践”,也没有必要刷新输出。
虽然 Drakosha 是正确的,调用
close
让您可以检查流的失败位,但无论如何,没有人这样做。在理想的情况下,只需事先调用stream.exceptions(ios::failbit)并处理fstream析构函数中引发的异常。但不幸的是,析构函数中的异常在 C++ 中是一个被破坏的概念,所以这不是一个好主意。
因此,如果您想检查关闭文件是否成功,请手动执行(但仅在此时)。
I think the previous answers are misleading.
fstream
is a proper RAII object, it does close automatically at the end of the scope, and there is absolutely no need whatsoever to callclose
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.
And while Drakosha is right that calling
close
gives you the possibility to check the fail bit of the stream, nobody does that, anyway.In an ideal world, one would simply call
stream.exceptions(ios::failbit)
beforehand and handle the exception that is thrown in anfstream
’s destructor. But unfortunately exceptions in destructors are a broken concept in C++ so that’s not a good idea.So if you want to check the success of closing a file, do it manually (but only then).