How can I check if a file has read permissions in C?
755 - owner can read/write/execute, group/others can read/execute. 644 - owner can read/write, group/others can read only.
Permissions of 644 mean that the owner of the file has read and write access, while the group members and other users on the system only have read access.
755 means read and execute access for everyone and also write access for the owner of the file. When you perform chmod 755 filename command you allow everyone to read and execute the file, the owner is allowed to write to the file as well.
F_OK: Used to check for existence of file. R_OK: Used to check for read permission bit. W_OK: Used to check for write permission bit. X_OK: Used to check for execute permission bit.
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).
I'm a fan of using stat(), myself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With