Linux下C语言判断文件是否存在

代码如下,

#include 
#include 

int main(void)
{
    if (access("AA.txt", F_OK) == 0)
    {
        printf("AA.txt exists.\n");
    }
    else
    {
        printf("AA.txt not exists.\n");
    }
    
    return 0;
}

简要分析

使用unistd.h里的函数access()来判断文件是否存在,其原型如下,

// return 0 if OK; return −1 on error
int access(const char *pathname, int mode); 

pathname就是文件名(可包含路径),mode的取值有以下几种,可以使用或操作(OR)来组合,

mode Description
F_OK 测试文件是否存在
R_OK 测试文件是否有读权限
W_OK 测试文件是否有写权限
X_OK 测试文件是否有执行权限

你可能感兴趣的:(C/C++,linux)