linux文件-access函数

91 篇文章 4 订阅
66 篇文章 1 订阅

 access函数:

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

 #include <unistd.h>

       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 <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>


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 <fcntl.h>           /* Definition of AT_* constants */
       #include <unistd.h>

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

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Achou.Wang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值