C++ 关闭文件
示例
在C++中,几乎不需要显式关闭文件,因为文件流将自动在其析构函数中关闭其关联文件。但是,您应该尝试限制文件流对象的生存期,以便它不会使文件句柄打开的时间超过必需的时间。例如,可以通过将所有文件操作放在自己的作用域({})中来完成此操作:
std::string const prepared_data = prepare_data(); { //打开文件进行写入。 std::ofstream output("foo.txt"); //写数据。 output << prepared_data; } //该ofstream将超出范围。 //它的析构函数将负责正确关闭文件。
close()仅当您要fstream稍后重用同一对象,但又不想让文件保持打开状态时,才需要显式调用:
// Open the file "foo.txt" for the first time. std::ofstream output("foo.txt"); //获取一些要从某个地方写入的数据。 std::string const prepared_data = prepare_data(); // Write data to the file "foo.txt". output << prepared_data; // Close the file "foo.txt". output.close(); //准备数据可能需要很长时间。因此,我们不会打开输出文件流 //在我们实际可以写入一些数据之前。 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();