C++ std::basic_fstream::close

C++ std::basic_fstream::close


Closes the associated file.
                                                                 void close();
The Library effectively calls rdbuf()->close(). This function is called by the destructor of basic_fstream when the stream object goes out of scope and is not usually invoked directly. 
If an error occurs during operation, setstate(failbit) is called.


#include <fstream>

using namespace std;

int main(int argc,char **argv)
fstream fstrm("fstream.txt", ios::in|ios::out|ios::trunc);
        //Writing into the file by object.
        fstrm<<"Writing to a basic_fstream object"<<endl;
        cout << fstrm.is_open()<<endl;
        fstrm.close();                          //called by the destructor of object of basic_fstream
        cout << fstrm.is_open()<<endl;
return 0;



After writing into the file, it has been checked whether file is open or not. Since close() was not called, it was open. But after close() was called, file had been disconnected from the fstream object. Therefore, we get output to be boolean '1' for true as file had been open and boolean '0' for false as file had been closed.