简体   繁体   中英

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.

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

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

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 (ie, 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM