When your program accesses a file, whether to read it, write to it, or both, it goes through the following steps.
The file first must be opened. This establishes a path of communication between the file and a stream object in your program fstream, ofstream , or ifstream used to access the file.
Your program then reads from, or writes to, the file (or both). This section will discuss writing to a file before reading to it, but in your program the order could be reversed . Additionally, your program may only read from a file, or only write to a file.
Finally, your program closes the file. Maintaining the path of communication between the file and the stream object in your program requires system resources, so closing the file frees those resources when they are no longer needed. Additionally, you may not be able to access the file later in your program if you did not close it after the previous access.