Search code examples
c++file-iofilesystemsfile-permissions

Checking for file existence in C++


Currently I use something like:

#include <sys/stat.h>

#include "My_Class.h"

void My_Class::my_function(void)
{
  std::ofstream my_file;

  struct stat file_info; 

  if ( filename_str.compare("")!=0  &&
       stat(filename_str.c_str(),&file_info) == 0 )
  {
    my_file.open(filename_str.data(),std::ios::trunc);
    //do stuff
    my_file.close(); 
  }
  else if ( filename_str.compare("")==0 )
  {
    std::cout << "ERROR! ... output filename not assigned!" << std::endl;
  }
  else
  {
    std::cout << "ERROR! File :" << std::endl
          << filename_str << std::endl 
          << "does not exist!!" << std::endl;
  }
}

...is this a decent way to go, or is there a better alternative? Seems like I could run amuck of permissions if I don't have permissions to read the file.

This is NOT a homework, question, it is a question about best practice.


Solution

  • Generally I think it is best to just try opening it and catch an error.

    IMO, checking permissions is unwise because what if it's a Linux box and you check its attributes, decide you can't write to it, but the filesystem supports ACL's and they do grant you permission? (As a sysadmin I can't stand when apps do this. I like ACL's and if you're an app, don't tell me you can't write to a file unless you've tried first.)