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; }

10th Sep 2018, 3:39 PM
Storm_CR
Storm_CR - avatar
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
10th Sep 2018, 3:52 PM
KrOW
KrOW - avatar
10th Sep 2018, 3:39 PM
Storm_CR
Storm_CR - avatar
+ 1
Ok, thanks guys
10th Sep 2018, 3:55 PM
Storm_CR
Storm_CR - avatar
+ 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.
10th Sep 2018, 6:53 PM
Sergey Ushakov
Sergey Ushakov - avatar