關閉檔案

在 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();