关闭文件
在 C++中很少需要显式关闭文件,因为文件流将自动在其析构函数中关闭其关联文件。但是,你应该尝试限制文件流对象的生命周期,这样它就不会使文件句柄保持打开的时间超过必要的时间。例如,这可以通过将所有文件操作放入自己的范围({}
)来完成:
std::string const prepared_data = prepare_data();
{
// Open a file for writing.
std::ofstream output("foo.txt");
// Write data.
output << prepared_data;
} // The ofstream will go out of scope here.
// Its destructor will take care of closing the file properly.
只有在以后想要重用相同的 fstream
对象但不想在两者之间保持文件打开时,才需要显式调用 close()
:
// Open the file "foo.txt" for the first time.
std::ofstream output("foo.txt");
// Get some data to write from somewhere.
std::string const prepared_data = prepare_data();
// Write data to the file "foo.txt".
output << prepared_data;
// Close the file "foo.txt".
output.close();
// Preparing data might take a long time. Therefore, we don't open the output file stream
// before we actually can write some data to it.
std::string const more_prepared_data = prepare_complex_data();
// Open the file "foo.txt" for the second time once we are ready for writing.
output.open("foo.txt");
// Write the data to the file "foo.txt".
output << more_prepared_data;
// Close the file "foo.txt" once again.
output.close();