In C on Unix, how can a process tell what permissions it has to a file without opening it?

馋奶兔 提交于 2019-12-06 15:26:05

The access() POSIX function can check the permissions without opening it. However, it needs to a syscall.

The access() function shall check the file named by the pathname pointed to by the path argument for accessibility according to the bit pattern contained in amode, using the real user ID in place of the effective user ID and the real group ID in place of the effective group ID.

For example:

access("/etc/passwd",W_OK)

checks if you have write access to the passwd file. With R_OK, read permissions are checked.

The eaccess() function (euidaccess is a synonym) uses the effective user and group id. While eaccess seems to be widely supported, as far as I know it is not part of the POSIX standard.

unistd.h defines an access() function,

int access(const char *path, int amode);

where path is your filename and amode is a bitwise inclusive OR of access permissions to check against.

R_OK, W_OK, and X_OK hold mode values for checking read, write, and search/execute permissions respectively.

int readable, readwritable;

//checking for read access
readable = access("/usr/bin/file", R_OK);

//checking for read and write access
readwritable = access("/usr/bin/file", R_OK|W_OK);

You can find a full description of access() in the unix man pages.

The acccess() checks the file name pointed by the path argument. The drawback here is each file permission has to be chekced individually using the flags below. R_OK Test for read permission. W_OK Test for write permission. X_OK Test for execute or search permission. F_OK Check existence of file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!