Checking for file presence in C ++

I am currently using 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? It looks like I could run permission permissions if I don't have read permissions on the file.

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

+3
c ++ filesystems file-io file-permissions
source share
3 answers

In general, I think the best thing is to simply try to open it and catch the error.

IMO, checking permissions is unreasonable, because if this is a Linux field and you are checking its attributes, decide that you cannot write to it, but the file system supports ACLs and they give you permission? (As a system administrator, I cannot stand when applications do this. I like the ACL, and if you are an application, do not tell me that you cannot write to a file if you have not tried it first.)

+3
source share

I would use boost :: filesystem constructs. They not only cross the platform, but are also part of the next standard library.

+4
source share

Conceptually, I would say it depends on what you plan to do with this file.

  • If you need its contents, go ahead and try to open it, and be prepared to handle the failure gracefully, for the reasons described by Ken.
  • If you are not currently interested in its contents (for example, when listing the contents of a directory or planning access to a file at some point in the future, etc.), you might be better off just checking the attributes for now. Otherwise, unpleasant things, such as hierarchical storage management, can cause an expensive (= slow) call to the contents of a file, say, from a tape or network backup (while attributes can be cached). You can try to avoid this by checking the appropriate file attributes, but also the added complexity.

So, as a best practice, I suggest opening files sparingly (i.e. if you are not immediately interested in the content, rely on information based on file-based attributes), and handle the failure strictly in response to the actual call that the file opens, when you need it.

0
source share

All Articles