Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 864
Jason R. Mick Avatar asked Dec 13 '25 19:12

Jason R. Mick


1 Answers

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

like image 161
Edward Strange Avatar answered Dec 15 '25 07:12

Edward Strange



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!