Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c read a file's permissions

Tags:

c

permissions

How can I check if a file has read permissions in C?

like image 896
Señor Reginold Francis Avatar asked Sep 16 '09 00:09

Señor Reginold Francis


People also ask

What does Permission 644 and 755 mean for a file?

755 - owner can read/write/execute, group/others can read/execute. 644 - owner can read/write, group/others can read only.

What does chmod 644 mean?

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.

How do I check permissions 755?

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.

How can we know read/write permission any given file in C?

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.


2 Answers

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).

like image 179
caf Avatar answered Oct 04 '22 01:10

caf


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

like image 36
user47559 Avatar answered Oct 04 '22 01:10

user47559