Skip to main content

12.3) Closing Files


ofstream outfile("out.txt");
if (not outfile.is_open()) {
  // Deal with failure to open file
}
// Code to write to file goes here
outfile.close();   // IMPORTANT: don't forget to do this!
  • To close a file stream, call its close method
  • It isn't strictly necessary to close ifstream objects after use but it is advisable to do so - e.g., to keep the number of open files under the limit imposed by your operating system, or to allow that ifstream object to be reused with other files later
  • It is very important to close ofstream objects after use, to ensure that any buffered output data gets delivered to the file on disk