How can I check if a file has read permissions in C?
相关问题
- Multiple sockets for clients to connect to
- What is the best way to do a search in a large fil
- Django check user group permissions
- glDrawElements only draws half a quad
- Index of single bit in long integer (in C) [duplic
Use the access() function:
errno
will be set toENOENT
if the file doesn't exist, orEACCES
if it exists but isn't accessible to the current user. See the manual page for more error codes.Use
access(2)
in POSIX. In Standard C, the best you can do is try to open it withfopen()
and see if it succeeds.If
fopen()
returnsNULL
, you can try to useerrno
to distinguish between the "File does not exist" (errno == ENOENT
) and "Permission denied" (errno == EACCES
) cases - but unfortunately those twoerrno
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).I'm a fan of using stat(), myself.