Detecting reason for failure to open an ofstream when fail() is true

前端 未结 4 495
北荒
北荒 2020-12-06 16:16

Seems like this should be simple, but I don\'t find it in a net search.

I have an ofstream which is open(), and fail() is now true. I\'d li

相关标签:
4条回答
  • 2020-12-06 17:01

    This is portable but doesn't appear to give useful info:

    #include <iostream>
    using std::cout;
    using std::endl;
    #include <fstream>
    using std::ofstream;
    
    int main(int, char**)
    {
        ofstream fout;
        try
        {
            fout.exceptions(ofstream::failbit | ofstream::badbit);
            fout.open("read-only.txt");
            fout.exceptions(std::ofstream::goodbit);
            // successful open
        }
        catch(ofstream::failure const &ex)
        {
            // failed open
            cout << ex.what() << endl; // displays "basic_ios::clear"
        }
    }
    
    0 讨论(0)
  • 2020-12-06 17:07

    we need not use std::fstream, we use boost::iostream

    #include <boost/iostreams/device/file_descriptor.hpp>
    #include <boost/iostreams/stream.hpp>
    
    void main()
    {
       namespace io = boost::iostreams;
    
       //step1. open a file, and check error.
       int handle = fileno(stdin); //I'm lazy,so...
    
       //step2. create stardard conformance streem
       io::stream<io::file_descriptor_source> s( io::file_descriptor_source(handle) );
    
       //step3. use good facilities as you will
       char buff[32];
       s.getline( buff, 32);
    
       int i=0;
       s >> i;
    
       s.read(buff,32);
    
    }
    
    0 讨论(0)
  • 2020-12-06 17:08

    The strerror function from <cstring> might be useful. This isn't necessarily standard or portable, but it works okay for me using GCC on an Ubuntu box:

    #include <iostream>
    using std::cout;
    #include <fstream>
    using std::ofstream;
    #include <cstring>
    using std::strerror;
    #include <cerrno>
    
    int main() {
    
      ofstream fout("read-only.txt");  // file exists and is read-only
      if( !fout ) {
        cout << strerror(errno) << '\n'; // displays "Permission denied"
      }
    
    }
    
    0 讨论(0)
  • 2020-12-06 17:14

    Unfortunately, there is no standard way of finding out exactly why open() failed. Note that sys_errlist is not standard C++ (or Standard C, I believe).

    0 讨论(0)
提交回复
热议问题