在linux环境下使用access函数可以获取文件的属性信息(是否存在,是否可读,是否可写,是否可执行)。
1. 相关头文件
#include <unistd.h>
2.access 函数原型
/***********************************
** description : 检测文件的属性
** parameter:
** pathname:需要检测的文件名字
** mode:检测该文件是否具备的属性,参数值如下:
** F_OK:是否存在
** R_OK:是否可读
** W_OK:是否可写
** X_OK:是否可执行
** return:检测属性有效 成功:0, 失败:-1
************************************/
int access(const char *pathname, int mode);
3.举例
int main(int argc, char *argv[])
{
char *file_path_name = "/home/linux/text.txt";
if (access(file_path_name, F_OK) == 0)
{
fprintf(stdout, "file exist, ");
}
else
{
fprintf(stdout, "not exist, ", name);
return -1;
}
if (access(file_path_name, R_OK) == 0)
{
fprintf(stdout, "has read premission, ");
}
else
{
fprintf(stdout, "does not have read premission, ");
}
if (access(file_path_name, W_OK) == 0)
{
fprintf(stdout, "has write premission, ");
}
else
{
fprintf(stdout, "does not have write premission, ");
}
if (access(file_path_name, X_OK) == 0)
{
fprintf(stdout, "has execute premission\n");
}
else
{
fprintf(stdout, "does not have execute premission\n");
}
return 0;
}