一、windows下使用_access()或linux下使用access()函数
windows下使用_access()函数
所在头文件:<io.h> 函数原型:int _access(const char* _Filename, int _AccessMode); _Filename:文件或文件夹(目录)路径,可为绝对路径、相对路径; _AccessMode:指定判断的模式,包含4种; _AccessMode=00 表示只判断是否存在 _AccessMode=02 表示文件是否可执行 _AccessMode=04 表示文件是否可写 _AccessMode=06 表示文件是否可读 函数返回值:如果指定的方式有效,则此函数返回0,否则返回-1。 示例:
#include <io.h>
#include <iostream>
using namespace std;
int main()
{
char resPath[260]="./CamIntrinCalibRes.yml";
if (_access(resPath, 0) == 0)
printf("file exists!\n");
if (_access(resPath, 2) == 0)
printf("file can be executed!\n");
if (_access(resPath, 4) == 0)
printf("file can be written!\n");
if (_access(resPath, 6) == 0)
printf("file can be read!\n");
system("pause");
return 0;
}
输出: 
若在Windows下使用access()时,
 程序报如下错误,  错误原因: access()函数是符合POSIX标准的函数,在VS中这个标准已经过时,被ISO C++取代。在ISO C++标准下,该函数的名称为_access()。 解决方法: 1. 使用错误提示的方法,将函数更换为_access(); 2. 项目-属性-C/C+±预处理器中加入“_CRT_NONSTDC_NO_WARNINGS”,保存后重新编译项目即可  2. 在使用access()所在.cpp第一条语句位置加上 #define _CRT_NONSTDC_NO_WARNINGS ,重新编译即可,原理和2一样。 
linux下使用access()函数
头文件:<unistd.h> 函数原型:int access(const char *pathname, int mode); pathname:文件或文件夹(目录)路径,可为绝对路径、相对路径; mode:指定判断的模式,包含4种; mode=F_OK 只判断是否存在 mode=X_OK 判断是否有执行权限 mode=W_OK 只判断是否有写权限 mode=R_OK 只判断是否有读权限 函数返回值:如果指定的方式有效,则此函数返回0,否则返回-1。 进行windows<->linux平台移植时需要根据函数变化进行修改。
后续待补充
感谢各位朋友的:点赞、收藏和评论~
参考链接: C语言中access/_access函数的使用 _CRT_NONSTDC…与_CRT_SECURE… C/C++ 中判断某一文件或目录是否存在
|