c read a file's permissions

戏子无情 提交于 2020-03-18 14:54:36

问题


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


回答1:


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




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/1430240/c-read-a-files-permissions

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