C/C++中判断某一文件或目录是否存在

本文介绍了四种检测文件或目录是否存在的方法:使用C++简单实现、利用C语言库函数_access、Windows API函数FindFirstFile及Boost库的filesystem类。这些方法适用于不同场景下的文件存在性检查。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
1.C++很简单的一种办法:
2.利用 c 语言的库的办法:

函数名: _access
功  能: 确定文件的访问权限
用  法: int access(const char *filename, int amode);

Determine file-access permission.

int _access( const char *path, int mode );

int _waccess( const wchar_t *path, int mode );

参考MSDN

Return Value

Each of these functions returns 0 if the file has the given mode. The function returns –1 if the named file does not exist or is not accessible in the given mode; in this case, errno is set as follows:

EACCES

Access denied: file’s permission setting does not allow specified access.

ENOENT

Filename or path not found.

Parameters

path

File or directory path

mode

Permission setting

Remarks

When used with files, the _access function determines whether the specified file exists and can be accessed as specified by the value of mode . When used with directories, _access determines only whether the specified directory exists; in Windows NT, all directories have read and write access.

mode Value            Checks File For
00                              Existence only
02                              Write permission
04                              Read permission
06                              Read and write permission

 

Generic-Text Routine Mappings

TCHAR.H Routine _UNICODE & _MBCS Not Defined_MBCS Defined_UNICODE Defined
_taccess_access_access_waccess

Example

 

Output

File ACCESS.C exists
File ACCESS.C has write permission

 

 

3.在windows平台下用API函数FindFirstFile(...):

(1)检查文件是否存在:

 

(2)检查某一目录是否存在:

 

4.使用boost的filesystem类库的exists函数

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值