When will ofstream::open fail?

前端 未结 3 1649
时光说笑
时光说笑 2020-12-03 10:44

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 th

3条回答
  •  忘掉有多难
    2020-12-03 11:14

    To get ofstream::open to fail, you need to arrange for it to be impossible to create the named file. The easiest way to do this is to create a directory of the exact same name before running the program. Here's a nearly-complete demo program; arranging to reliably remove the test directory if and only if you created it, I leave as an exercise.

    #include 
    #include 
    #include 
    #include 
    #include 
    
    using std::ofstream;
    using std::strerror;
    using std::cerr;
    
    int main() 
    {
        ofstream outfile;
    
        // set up conditions so outfile.open will fail:
        if (mkdir("test.txt", 0700)) {
            cerr << "mkdir failed: " << strerror(errno) << '\n';
            return 2;
        }
    
        outfile.open("test.txt");
        if (outfile.fail()) {
            cerr << "open failure as expected: " << strerror(errno) << '\n';
            return 0;
        } else {
            cerr << "open success, not as expected\n";
            return 1;
        }
    }
    

    There is no good way to ensure that writing to an fstream fails. I would probably create a mock ostream that failed writes, if I needed to test that.

提交回复
热议问题