I am trying out try, catch, throw statements in C++ for file handling, and I have written a dummy code to catch all errors. My question is in order to check if I have got these right, I need an error to occur. Now I can easily check infile.fail()
by simply not creating a file of the required name in the directory. But how will I be able to check the same for outfile.fail()
(outfile
is ofstream
where as infile
is ifstream
). In which case, will the value for outfile.fail()
be true?
sample code [from comments on unapersson's answer, simplified to make issue clearer -zack]:
#include <fstream> using std::ofstream; int main() { ofstream outfile; outfile.open("test.txt"); if (outfile.fail()) // do something...... else // do something else..... return 0; }
std::ofstream::open. Opens the file identified by argument filename , associating it with the stream object, so that input/output operations are performed on its content. Argument mode specifies the opening mode. If the stream is already associated with a file (i.e., it is already open), calling this function fails.
So no, we do not need to explicitly call fstream::close() to close the file. After open a file with fstream/ifstream/ofstream, it is safe to throw an exception without manually close the file first.
ofstream will close files when its destructor is called, i.e. when it goes out of scope.
Note that any open file is automatically closed when the fstream object is destroyed.
The open(2)
man page on Linux has about 30 conditions. Some intresting ones are:
char*
for the filename.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With