c语言:access函数

#include <stdio.h>
#include <unistd.h>

int main(void)
{
    /**
     *
     * unistd.h
     * int access(const char * pathname, int mode);
     * access()会检查是否可以读/写某一已存在的文件。
     *
     * pathname:
     *     待检测文件或文件夹
     * mode: (unistd.h库文件内描述如下)
     *     define F_OK        0     test for existence of file
     *     define X_OK        (1<<0)  test for execute or search permission
     *     define W_OK        (1<<1)  test for write permission
     *     define R_OK        (1<<2)  test for read permission
     *
     * return:
     *     0 sucess
     *     -1 fail
     *
     * mode可以使用数字并叠加进行多权限检测;
     */

    // 检测文件是否存在
    if(access("/tmp/test.log", F_OK) == 0)
        printf("/tmp/test.log exists\n");

    // 检测文件夹是否存在
    if(access("/tmp", F_OK) == 0)
    {
        printf("/tmp exists\n");
    }

    // 检测文件是否拥有读权限
    if(access("/tmp/test.log", F_OK) == 0)
    {
        printf("/tmp/test.log can be read\n");
    }

    // F_OK 0
    // X_OK 1
    // W_OK 2
    // R_OK 4
    // 使用数字检测文件是否存在
    if(access("/tmp/test.log", 0) == 0)
        printf("/tmp/test.log exists\n");

    // 数字合并检测 6 = 4 + 2,检测是否拥有读写权限
    if(access("/tmp/test.log", 6) == 0)
        printf("/tmp/test.log can be read and write\n");

    // 检测不具有权限
    if(access("/etc/passwd", 6) == -1)
        printf("/etc/passwd can not be read and write\n");

    // 检测执行权限
    if(access("./access", 1) == 0)
        printf("./access can be execute\n");

}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值