Reputation: 16936
How can I check if a file has read permissions in C?
Upvotes: 7
Views: 31866
Reputation: 11
There are many ways to check a files permissions.
A very simple method for finding out the permissions is int access(const char *path, int amode). As commented before, this method operates unless there is an error. There are a few flags that you may use:
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.
When the file doesn't have the correct permissions, an error is thrown that you can retrive with errno.
int fd = access("sample.txt", F_OK);
if(fd == -1){
printf("Error Number : %d\n", errno);
perror("Error Description:");
}
If you want to handle an error while retrieving a file address, use FILE *fopen(const char *filename, const char *mode). Like access() it has flags that you can check such as read or write. The difference is, fopen can use strings instead of constants and will return a FILE pointer.
FILE *pf = fopen ("fileName.txt", "rb");
Here is a good example of how to handle errors with fopen
A third file checking method is int chmod(const char *path, mode_t mode). chmod() is more useful than access() since it has more flags. Depending on what directory you are reading from it could be easier to just use access() but if you have many files of different permissions then chmod() would be more useful.
#include <sys/stat.h>
int chmod(const char *path, mode_t mode);
I know that this post is from 11 years ago. I just wanted to make a general synopsis of common file handling methods.
Upvotes: 1
Reputation: 239321
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).
Upvotes: 9
Reputation: 281825
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.
Upvotes: 7