[Top] access function -linux

Original link: http://www.cnblogs.com/james1207/p/3283577.html

Header Files

#include<unistd.h>


Defined Functions

int access(const char * pathname, int mode);


Function Description

Check that you can read / write to a file that already exists.

pathname: file / directory path

mode:

R_OK \ W_OK \ X_OK:  Check if the file has permission to read, write, and execute

F_OK: to determine whether the file exists

Because access () only for verification authority, does not care about the form or content of the document file, so if a directory is represented as "write", that can create a new file in the directory and other operations, rather than the meaning of this directory can It is treated as document processing. For example, you will find the DOS files are "enforceable" rights, but with execve () execution will fail.


The return value
    if all permissions checks are to be checked by a 0 value is returned, indicating success, as long as there is a permission is prohibited or -1.


Error code
    EACCESS parameter specifies the pathname of the file does not meet the required permission to test.
    EROFS To test write access to a file exists in the read-only file system.
    EFAULT pathname argument pointer memory accessible beyond.
    EINVAL mode parameter is incorrect.
    ENAMETOOLONG parameters pathname is too long.
    ENOTDIR parameter pathname is a directory.
    ENOMEM Insufficient memory core    
    ELOOP pathname parameter has too many symbolic links problem.
    EIO I / O access error.


Additional information
    using the access () to determine the certification for users to be especially careful, for example in access () before making open (), empty file can cause problems on your system security.


example:

Judgment test file if there is

#include <errno.h>

#include <unistd.h>

#include <stdio.h>

int main ()

{

int err = 0;

err = access("/home/test" , F_OK);

if ( err !=0 )

{

printf("erro!%d:%s\n", errno , strerror(errno ));

mkdir("/home/test", 0777);

printf("erro!%d : %s\n" , errno, strerror(errno));

}else

printf("direxit!\n");


return 0;

}

1、/home下test文件是否存在

如果传入的pathname是”/home/test"路径最后一个字符串不是斜杠’/’

结果如下:

root@VM-Ubuntu203001:~/test#./a.out

dir exit!

因为 test在/home下面是个文件,access判断这个文件已经存在,是正确的。


2、/home下test目录是否存在

如果传入的pathname是”/home/test/"路径最后一个字符串是斜杠’/’

结果如下:

root@VM-Ubuntu203001:~/test#./a.out

erro!20:Nota directory

erro! 17 : File exists

测试结果是,access 把/home目录下面的test文件当做目录了,最后发现test不是目录,所以报错了。

经过查找文档,


[注释:如果linux文件路径的最后一个字符是斜杠’/’,那么linux会把这个路径当做目录路径来处理,而不管路径中的目录名实际上是个已经存在的文件名。]



转载于:https://www.cnblogs.com/james1207/p/3283577.html

Guess you like

Origin blog.csdn.net/weixin_30648587/article/details/94986553