Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
629 views
in Technique[技术] by (71.8m points)

c++ - When will ofstream::open fail?

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; 
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...