Closing Files
Lesson 5 of 23 in Coddy's C++ File Handling course.
When a C++ program ends, it usually automatically flushes all streams that were in memory in order to free up memory and close all opened files. However, it is best practice to explicitly close the file whenever it is done using it.
Also, it's easier to not get confused about which file you have opened. For example, if you open 3 files at once you might try to read from the 3rd file when trying to read from the 2nd, so for that not to happen, you should close every file when you are done using it.
We close files using the close() method.
file.close();Challenge
EasyWrite only where you are allowed in the code and close the given file.
Try it yourself
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream my_file;
my_file.open("example.txt");
// Don't change from here above
// Don't change from here below
if(my_file.is_open())
cout << "File is still open.";
else
cout << "File successfully closed";
return 0;
}