Jason R. Mick
Jason R. Mick

Reputation: 5287

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.

Upvotes: 3

Views: 1203

Answers (4)

svv
svv

Reputation: 54

Since C++17 filesystem library is available and you should use this library. It provides std::filesystem::exists() call

Upvotes: 0

ig2r
ig2r

Reputation: 2394

Conceptually, I'd say it depends on what you're planning to do with that file..

  • If you need its contents, go ahead and try to open it, and be prepared to handle failure gracefully, for the reasons Ken detailed.
  • If you are not currently interested in its contents (for example, when enumerating directory contents, or only planning to access a file at some point in the future, etc.), you might be better off just checking attributes for now. Otherwise, nasty things like hierarchical storage management may trigger an expensive (=slow) recall of file contents from, say, a tape backup or network (whereas attributes may have been cached). You could try to avoid that by checking for respective file attributes, but that's additional complexity, too.

So as a best practice, I'd suggest to open files sparingly (i.e., if you're not immediately interested in the contents, contend yourself with file attribute-based information), AND handle failure strictly in response to the actual call that opens the file when you need it.

Upvotes: 0

Edward Strange
Edward Strange

Reputation: 40859

I'd use the boost::filesystem constructs. Not only are they cross platform, they're part of the next standard library.

Upvotes: 4

Ken Simon
Ken Simon

Reputation: 1544

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

Upvotes: 3

Related Questions