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

972 篇文章 329 订阅
148 篇文章 34 订阅

       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]$ 


      

 

      不消多说。

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值