views:

513

answers:

3

I have a relatively trivial question. How can I check if a file has read permissions in C?

thanks

+4  A: 

Use access(2) in POSIX. In Standard C, the best you can do is try to open it with fopen() and see if it succeeds.

If fopen() returns NULL, you can try to use errno to distinguish between the "File does not exist" (errno == ENOENT) and "Permission denied" (errno == EACCES) cases - but unfortunately those two errno values are only defined by POSIX as well.

(Even on POSIX, in most cases the best thing to do is try to open the file, then look at why it failed, because using access() introduces an obvious race condition).

caf
I would use fopen(), but I need to be able to tell the difference whether the file isnt readable and whether it doesnt exist
Steven1350
Using fopen will be better. Because access is vulnerable to TOCTOU attacks. (http://en.wikipedia.org/wiki/TOCTOU). If that is a concern in your case at all.
Szere Dyeri
+4  A: 

Use the access() function:

if (access(pathname, R_OK) == 0)
{
    /* It's readable by the current user. */
}

errno will be set to ENOENT if the file doesn't exist, or EACCES if it exists but isn't accessible to the current user. See the manual page for more error codes.

RichieHindle
+4  A: 

I'm a fan of using stat(), myself.