Of course, you are not going to close a file as soon as you open it. You will read or write to the file first. However, closing a file is relatively simple, so I will discuss this issue out of order before discussing the more complex subjects of writing to, and reading from, a file.
You should close a file when you are finished reading or writing to it. While the file object will be closed when the program ends, your programs performance will be improved if you close a file when you are finished with it because each open file requires system resources. Additionally, some operating systems limit the number of open handles to files. Finally, you will avoid a sharing problem caused by trying in one part of your program to open a file that in another part of the program previously was opened but not closed.
You close a file using, naturally enough, the close member function, which takes no arguments. The following example closes a file opened for writing:
ofstream outfile; outfile.open("students.dat"); // do something outfile.close();
The same syntax applies to closing a file for reading.
ifstream infile; infile.open("students.dat"); // do something infile.close();