What happens if you don't close a file (with example.close();)that you've opened? For example if one would run this code down below, what would happen? Would the computer go crazy and start erasing memory or something else dangerous? xD If it doesn't, what is the point of closing files after opening them?
when you make an instance of a class, you call the constuctor of that class upon declaration to initialize the variable. ie
string grej("Hello, world!");
fstream file("filename.txt"); http://www.cplusplus.com/doc/tutorial/classes/
In a broader context, that is thinking more widely than just C++ and fstream, when an output file is closed, any data remaining in the output buffer is written to the output file. If a file isn't closed properly, then some data may be missing from the file, or the file may be corrupted in some other way. But that's just background information.
Just as an added note, there are still situations where it is necessary to explicitly close a file. Say you have a vector fileNames of files you need to process.
1 2 3 4 5 6 7 8
for ( std::vector< std::string >::size_type i = 0; i < fileNames.size(); ++i )
inFile.open( fileNames[ i ] );
// code to process the file
The reason you need to call close() at the end of the loop is that trying to open a new file without closing the first file will fail. The call to clear() at the beginning of the loop is necessary because closing a file and then opening another file does not clear the stream.