fstream: closing a file

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?

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main(){
    string grej;
    fstream file;
    file.open("filename.txt");
    getline(file, grej);
}
closed account (Dy7SLyTq)
i think the deconstructor closes it
The file will be closed when fstream leaves the scope, which is the normal pattern of usage (incidentally, calling open() is unnecessary too, use the constructor to open the file)

In general, it only makes sense to call file.close() if you care about the exceptions it might throw or stream states it may set.
Last edited on
(incidentally, calling open() is unnecessary too, use the constructor to open the file)
What do you mean by "using the constructor"?
closed account (Dy7SLyTq)
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
std::ifstream inFile;
for ( std::vector< std::string >::size_type i = 0; i < fileNames.size(); ++i )
{
   inFile.clear();
   inFile.open( fileNames[ i ] );
   // code to process the file
   inFile.close();
}



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.

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.

Or you could change the code slightly:

1
2
3
4
5
for ( std::vector< std::string >::size_type i = 0; i < fileNames.size(); ++i )
{
    std::ifstream in(fileNames[i]) ;
   // code to process the file
}
Topic archived. No new replies allowed.