0
How to close file by destructor?
#include <iostream> #include <fstream> using namespace std; class file_handle{ public: void f(string s){ cin >> s; fstream file; file.open(s, ios::out | ios::in | ios::trunc); if(!file.is_open()){ cout << "Error while opening the file" <<endl; } else if(file.is_open()){ cout << "Success" << endl; file.close(); //How to close file by destructor? //Not by file.close() } } }; int main(){ string s; file_handle fh; fh.f(s); return 0; }
4 Answers
+ 3
You have to keep "file" life outside "f" scope.
In practice you have to put "file" like an attribute of class:
class file_handle{
private:
fstream file;
public:
~file_handle(){
if(file.is_open())
file.close();
}
...
};
Oblivious you have to manage it between all life of an "file_handle" object
+ 1
Ok, thanks guys
+ 1
file stream closes file at it's destructor. It means you are not required to write your own destructor to call close function. It is enough to place file stream to class members section.