Get a descriptive reason why std::ofstream open failed

104 Views Asked by At

Is there a standard/cross-platform way to throw a descriptive exception with the reason why the file failed to be opened? (Eg: "Read-only directory", "Permission denied", "File is open in another program" etc.)

I have SomeMethod that receives a file from some caller and I need to write to/create that file, and in case of errors, throw an exception.

I tried using the ofstream::exceptions member function like so:

void SomeMethod(std::string fileName)
{
  std::ofstream outFile;
  outFile.exceptions(std::ios::failbit | std::ios::eofbit);
  outFile.open(fileName);

  // start writing to file..
}

But the exception thrown is not descriptive enough. I get:

ios_base::failbit set: iostream stream error

I also tried using std::system_error:

void SomeMethod(std::string fileName)
{
  std::ofstream outFile(fileName);
  if (!outFile.is_open())
  {
    throw std::system_error(
#ifdef _WIN32
      ::GetLastError(),
#else
      errno,
#endif
      std::system_category(), "Error opening " + fileName);
  }

  // start writing to file..
}

which gives the descriptive error I want:

Error opening some_file.txt: Read-only file system

But, the code is a little too verbose. I was hoping for something shorter...

I created this playground: https://godbolt.org/z/b1zKKnEnz

0

There are 0 best solutions below