linux文件-access函数

 access函数:

access函数主要用于在使用文件之前获取文件的属性以免错误的使用文件的权限,造成文件读写过程中出错;

 #include 

       int access(const char *pathname, int mode);
成功返回0,出错返回-1
功能:检查是否可以对某文件进行某种操作
    F_OK 值为0,判断文件是否存在
    R_OK 值为4,判断对文件是否有读权限
    W_OK 值为2,判断对文件是否有写权限
    X_OK 值为1,判断对文件是否有读写权限

 坚持使用代码说话,编写access的函数并进行测试:

编写函数file_access.c函数,并编译运行进行测试测试结果如下:

andrew@andrew-Thurley:~/work/filedir$ ./a.out *
7852 can read a.out
7852 can write a.out
7852 can rexcute a.out
7852 can read bin
7852 can write bin
7852 can rexcute bin
7852 can read date.txt
7852 can write date.txt
7852 can not  excute date.txt
7852 can read include
7852 can write include
7852 can rexcute include
7852 can read l_date
7852 can write l_date
7852 can not  excute l_date
7852 can read obj
7852 can write obj
7852 can rexcute obj
7852 can read src
7852 can write src
7852 can rexcute src
7852 can read zieckey_fifo
7852 can write zieckey_fifo
7852 can rexcute zieckey_fifo

file_access.c函数:

#include 
#include 
#include 
#include 
#include 


int main(int argc, char *argv[])
{

    if(argc < 2)
    {
        fprintf(stderr, "usage: %s files \n", argv[0]);
        exit(1);
    }

    int i;
    for(i = 1; i < argc;  i++)
    {
        if(access(argv[i], R_OK))
        {
            printf("%d can not read %s\n", getpid(),argv[i]);
        }
        else
        {
            printf("%d can read %s\n", getpid(), argv[i]);
        }

        if(access(argv[i], W_OK))
        {
            printf("%d can not write %s\n", getpid(),argv[i]);
        }
        else
        {
            printf("%d can write %s\n", getpid(), argv[i]);
        }

        if(access(argv[i], X_OK))
        {
            printf("%d can not  excute %s\n", getpid(),argv[i]);
        }
        else
        {
            printf("%d can rexcute %s\n", getpid(), argv[i]);
        }
    }




    return 0;
}

 

  #include            /* Definition of AT_* constants */
       #include 

       int faccessat(int dirfd, const char *pathname, int mode, int flags);

 

 

 

 

 

 

你可能感兴趣的:(linux,嵌入式,嵌入式-Linux)