今天读代码看到一个access函数,当时没明白怎么回事。man了一下才知道该函数主要用于文件读取方面——判断文件是否存在,并判断文件是否可写。Linux下,该函数为access,位于头文件<unistd.h>中,而在标准C++中,该函数为_access,位于头文件<io.h>中,两者的使用方法基本相同,只是在一些参数方面可能会有一些不同的宏定义。下面是标准C++为例做一下总结:
头文件:<io.h>
函数原型:int _access(const char *pathname, int mode);
参数:pathname 为文件路径或目录路径 mode 为访问权限(在不同系统中可能用不能的宏定义重新定义)
返回值:如果文件具有指定的访问权限,则函数返回0;如果文件不存在或者不能访问指定的权限,则返回-1.
备注:当pathname为文件时,_access函数判断文件是否存在,并判断文件是否可以用mode值指定的模式进行访问。当pathname为目录时,_access只判断指定目录是否存在,在Windows NT和Windows 2000中,所有的目录都只有读写权限。
mode的值和含义如下所示:
00——只检查文件是否存在
02——写权限
04——读权限
06——读写权限
对应的还有_access的宽字符版本,用法相同。
例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
#include <io.h>
#include <stdio.h>
#include <stdlib.h>
int
main
(
)
{
if
(
(
_access
(
“IsExist.txt”
,
0
)
)
!=
-
1
)
{
printf
(
“File IsExist.txt exists.n”
)
;
if
(
(
_access
(
“IsExist.txt”
,
2
)
)
!=
-
1
)
printf
(
“File IsExist.txt does not have write permission.\n”
)
;
}
return
0
;
}
|