tags:

views:

114

answers:

2

In C++ how can I determine if the program has either read-only access or read-write access to a file? I searched the boost filesystem library but I have yet to find something to help me. Right now I thinking of opening the file, trying to write inside and check for error, but that doesn't seem a very appropriate way of doing this.

Any clue?

EDIT : it would need to be cross platform

+5  A: 

The system call, which most runtime libraries fully support, is

#include <unistd.h>

if (0 == access (char *pathname, int mode))
    // permission is granted

where mode is F_OK to test existence of file, or a mask consisting of the bitwise OR of one or more of R_OK, W_OK, and X_OK.

wallyk
+1 I didn't knew this !
Ben
According to the BSD system calls manual, the access() function is a potential security hole and should never be used. The Linux man pages note the security risk as well but do not state that the function should not be used.
jschmier
It's not a system call, and is only supported on POSIX systems.
anon
Simple and straightforward, I like that! However, it need to be cross platform so I can't use unistd.h ...
Laurent Bourgault-Roy
+5  A: 

At the end of the day, the only way to test if you can write data to a file on a modern OS is to actually try to write it. Lots of things could have happened to the file between tests for permission and the actual write.

anon