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

烈酒焚心 提交于 2019-11-28 00:42:39

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).

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"
  }

}
mheyman

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"
    }
}

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);

}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!