Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When will ofstream::open fail?

Tags:

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;  } 
like image 723
Scranton Avatar asked Apr 29 '11 18:04

Scranton


People also ask

Does ofstream open the file?

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.

Does ofstream need to be closed?

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.

Does ofstream destructor close file?

ofstream will close files when its destructor is called, i.e. when it goes out of scope.

Does fstream close on destruction?

Note that any open file is automatically closed when the fstream object is destroyed.


1 Answers

The open(2) man page on Linux has about 30 conditions. Some intresting ones are:

  • If the file exists and you don't have permission to write it.
  • If the file doesn't exist, and you don't have permission (on the diretory) to create it.
  • If you don't have search permission on some parent directory.
  • If you pass in a bogus char* for the filename.
  • If, while opening a device file, you press CTRL-C.
  • If the kernel encountered too many symbolic links while resolving the name.
  • If you try to open a directory for writing.
  • If the pathname is too long.
  • If your process has too many files open already.
  • If the system has too many files open already.
  • If the pathname refers to a device file, and there is no such device in the system.
  • If the kernel has run out of memory.
  • If the filesystem is full.
  • If a component of the pathname is not a directory.
  • If the file is on a read-only filesystem.
  • If the file is an executable file which is currently being executed.
like image 183
Robᵩ Avatar answered Sep 19 '22 15:09

Robᵩ