c read a file's permissions

2019-05-01 00:31发布

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

标签: c permissions
3条回答
Explosion°爆炸
2楼-- · 2019-05-01 01:14

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.

查看更多
Bombasti
3楼-- · 2019-05-01 01:22

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

查看更多
劳资没心,怎么记你
4楼-- · 2019-05-01 01:28

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

查看更多
登录 后发表回答