您的位置:首页 > 运维架构 > Linux

玩玩linux下的access函数---探测文件/目录权限

2015-05-06 22:53 489 查看
       access函数用来探测文件/目录权限, 我们先来看程序:

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

int main()
{
char szTest[][100] =
{
"ls",
"touch test",  // 此时, test是文件
"chmod u-rwx test",
"chmod u+r test",
"chmod u+w test",
"chmod u+x test",
};

int i = 0;
int n = sizeof(szTest) / sizeof(szTest[0]);
for(i = 0; i < n; i++)
{
system(szTest[i]);

if(1 == i)
{
continue;
}

if(access("test", F_OK) < 0)
{
perror("e0");
}
else
{
printf("file ok\n");
}

if(access("test", R_OK) < 0)
{
perror("e1");
}
else
{
printf("read ok\n");
}

if(access("test", W_OK) < 0)
{
perror("e2");
}
else
{
printf("write ok\n");
}

if(access("test", X_OK) < 0)
{
perror("e3");
}
else
{
printf("exec ok\n");
}
}

return 0;
}
      结果为:

 [taoge@localhost learn_c]$ ls

test.c

[taoge@localhost learn_c]$ gcc test.c 

[taoge@localhost learn_c]$ ./a.out 

a.out  test.c

e0: No such file or directory

e1: No such file or directory

e2: No such file or directory

e3: No such file or directory

file ok

e1: Permission denied

e2: Permission denied

e3: Permission denied

file ok

read ok

e2: Permission denied

e3: Permission denied

file ok

read ok

write ok

e3: Permission denied

file ok

read ok

write ok

exec ok

[taoge@localhost learn_c]$ 

        我们再来看目录, 代码如下:

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

int main()
{
char szTest[][100] =
{
"ls",
"mkdir test",  // 此时, test是目录, 不再是"touch test"生成的文件
"chmod u-rwx test",
"chmod u+r test",
"chmod u+w test",
"chmod u+x test",
};

int i = 0;
int n = sizeof(szTest) / sizeof(szTest[0]);
for(i = 0; i < n; i++)
{
system(szTest[i]);

if(1 == i)
{
continue;
}

if(access("test", F_OK) < 0)
{
perror("e0");
}
else
{
printf("directory ok\n");
}

if(access("test", R_OK) < 0)
{
perror("e1");
}
else
{
printf("read ok\n");
}

if(access("test", W_OK) < 0)
{
perror("e2");
}
else
{
printf("write ok\n");
}

if(access("test", X_OK) < 0)
{
perror("e3");
}
else
{
printf("exec ok\n");
}
}

return 0;
}
      结果为:

 [taoge@localhost learn_c]$ ls

test.c

[taoge@localhost learn_c]$ gcc test.c 

[taoge@localhost learn_c]$ ./a.out 

a.out  test.c

e0: No such file or directory

e1: No such file or directory

e2: No such file or directory

e3: No such file or directory

directory ok

e1: Permission denied

e2: Permission denied

e3: Permission denied

directory ok

read ok

e2: Permission denied

e3: Permission denied

directory ok

read ok

write ok

e3: Permission denied

directory ok

read ok

write ok

exec ok

[taoge@localhost learn_c]$ 

      

      不消多说。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: