在C++中,access()函数主要用于检查文件的访问权限(还可以用于判断文件是否存在)。这个函数并不是C++标准库的一部分所以使用的时候需要引入头文件#include <unistd.h>
在unistd 文件中 定义如下
int access(const char* __path, int __mode);
返回的是一个int值
当这个值为0的时候表示文件具有所请求的所有权限 此时是成功返回
当这个值为-1的时候表示出错或者进程没有所请求的权限之一
__path:一个指向包含路径名的字符串的指针,该路径指向要检查权限的文件或目录
__mode:指定要测试的访问类型
F_OK:检查文件是否存在。
R_OK:检查是否具有读取权限。
W_OK:检查是否具有写入权限。
X_OK:检查是否具有执行权限。
#include <iostream>
#include <string>
#include <unistd.h>
bool isOK(const std::string &filePath) {
int result = access(filePath.c_str(), R_OK);
return result == 0;
}
int main() {
const char* filePath = "/home/hly/test.txt";
// 逻辑判断
if (isOK(filePath)) {
std::cout << "File is readable." << std::endl;
} else {
std::cout << "File is not readable or accessible." << std::endl;
}
// 输出原始的返回值,如果没有问题返回是0,否则返回值是-1
std::cout << "Access function returned: " << access(filePath, R_OK) << std::endl;
return 0;
}