0
点赞
收藏
分享

微信扫一扫

终于把Linux中的access搞懂了 (内附C语言测试代码)

MaxWen 2022-03-11 阅读 48
#include <unistd.h>
int access(const char* pathname,int mode);

参数:

pathname 是文件的路径名+文件名

mode:指定access的作用,取值如下

F_OK 判断文件是否存在

X_OK 判断对文件是可执行权限

W_OK 判断对文件是否有写权限

R_OK 判断对文件是否有读权限

注意:后三种可以使用或“|”的方式,一起使用如 W_OK | R_OK

返回值:成功返回0,失败返回-1

#include <unistd.h>
#include <stdio.h>
int main()
{
int ret=access("test",F_OK);
if(ret==0)
{
printf("文件存在\n");
}
if(ret==-1)
{
printf("文件不存在\n");
}
return 0;
}

当我在当前目录下创建一个test文件时,编译gcc  access.c  -o ace时,编译成功,然后输入命令./ace,显示“文件存在”。当我把test文件删除后,再次执行./ace时,显示“文件不存在”。

 测试文件是否可读

  1 #include <unistd.h>
2 #include <stdio.h>
3 int main()
4
{
5 int ret=access("test",R_OK);
6 if(ret==0)
7 {
8 printf("文件可读\n");
9 }
10 else if(ret==-1)
11 {
12 printf("文件不存在\n");
13 }
14
15 return 0;
16 }

结果输出为:

 测试文件是否可读可写

  1 #include <unistd.h>
2 #include <stdio.h>
3 int main()
4
{
5 int ret=access("test",R_OK | W_OK);
6 if(ret==0)
7 {
8 printf("文件可读可写\n");
9 }
10 else if(ret==-1)
11 {
12 printf("文件不存在\n");
13 }
14
15 return 0;
16 }

测试输出结果

 不错,今天又学会一个函数的运用。

举报

相关推荐

0 条评论