What is the best way to check file existence and file permissions in Linux using C ++

I use boost::filesystem::exists() to check for the existence of a file.

Is there a better way to do this?

Also how to find file permissions?

+6
c ++ boost
source share
4 answers

The only correct way to check if a file exists is to try opening it. The only correct way to check if a file is writable is to try opening it for writing. Everything else is a race condition. (Other API calls may tell you if the file existed some time ago, but even if it did, there might not have been those 15 nanoseconds later when you try to open it, so they are pretty much useless.)

However, if you want to know if a file exists without opening it, just use the boost::filesystem::exists function. But keep in mind that there is a flaw. It does not tell you if the file exists, it tells you if the file exists.

So be careful how you use it. Do not assume that just because the function returned true, this file will exist when you really try to open it.

If you need to know, “I can open this file,” then the only way to find out is to try opening it.

+19
source share

I do not think that a formatted file system will provide you with any permission information.

I would go for a low level path (which is very simple for this case anyway): use the POSIX C API to check for file existence and permissions: use `stat.


Example:

 #include <sys/stat.h> #include <iostream> int main(int argc, char *argv[]) { struct stat sb; if( stat("file", &sb) == -1 ) { std::cout << "Couldn't stat(). Cannot access file, could assume it doesn't exist" << std::endl; return 1; } std::cout << "Permissions: " << std::oct << (unsigned long) sb.st_mode << std::endl; return 0; } 

Launch:

 $ ./stat Couldn't stat(). Cannot access file, could assume it doesn't exist $ touch file $ ./stat Permissions: 100644 
+5
source share

Could you just open the file with fopen() and check if the return value is null ?

+4
source share

Using boost is a portable way, of course.

But if you are really only interested in Linux, you can use access (2) , which will tell you if the file exists and whether you can handle it the way you want (and maybe not trigger an audit warning).

+4
source share

All Articles