【C/C++】access()判断文件是否存在
#include <unistd.h>int access(const char \*pathname, int mode);pathname:指定要检查的文件路径;支持相对路径(以执行程序所在目录为当前目录)。mode:名称、值及描述见下表。
| Mode | Value | Description | 
|---|---|---|
| F_OK | 0 | test for existence of file | 
| X_OK | 1 | test for execute or search permission | 
| W_OK | 2 | test for write permission | 
| R_OK | 4 | test for read permission | 
当mode值取为F_OK时,则用于判断文件是否存在;返回值为0表示存在;否则返回-1。
当mode取值为其它时,则用于判断文件存在且是否有相应的权限;返回值为0表示存在且相应的权限;否则返回-1。mode支持OR操作,同时判断X_OK W_OK R_OK的任意组合。
示例代码如下:
| 1 | /** | 
使用示例:
| 1 | if (existFile("file.name")) { | 
后记:
access()判断失败时,可能的错误代码为:
错误码皆在errno.h中定义。
EACCESS 参数pathname 所指定的文件不符合所要求测试的权限。
EROFS 欲测试写入权限的文件存在于只读文件系统内。
EFAULT 参数pathname指针超出可存取内存空间。
EINVAL 参数mode 不正确。
ENAMETOOLONG 参数pathname太长。
ENOTDIR 参数pathname为一目录。
ENOMEM 核心内存不足
ELOOP 参数pathname有过多符号连接问题。
EIO I/O 存取错误。