无法打开文件时我应该关闭文件吗?
我应该这样写吗:
std::ifstream file(DATA_PATH);
if (!file.good()) //File doesn't exist
{
//do something
}
else //file exists
{
//do something
file.close();
}
还是我应该写:
std::ifstream file(DATA_PATH);
if (!file.good()) //File doesn't exist
{
//do something
}
else //file exists
{
//do something
}
file.close();
最佳答案
不,没有必要明确地做。 (文件)流总是在隐式超出范围时关闭。close()
的std::iostream()
函数也是幂等操作,并且在流被关闭(或从未成功打开)之后,永远不会损害流的状态。
关于c++ - 无法打开文件时我应该关闭文件吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54316266/