在linux系统开发过程中,判断指定路径的文件是否存在是极为常见的需求,linux系统本身提供了多个标准函数来实现这个功能,不同函数的判断逻辑和适用场景各有不同,开发者可以根据实际需求选择合适的函数使用。

常用的判断文件存在的函数
1. access函数
access函数是unistd.h头文件中提供的函数,主要用于检查调用进程对指定文件的访问权限,同时也可以通过指定对应权限模式来判断文件是否存在。它的函数原型如下:
#include <unistd.h> int access(const char *pathname, int mode);
参数说明:
- pathname:需要检查的文件路径字符串
- mode:检查的权限模式,常用的模式有F_OK(判断文件是否存在)、R_OK(判断是否有读权限)、W_OK(判断是否有写权限)、X_OK(判断是否有执行权限),多个模式可以用按位或组合
返回值:如果检查通过返回0,失败返回-1并设置errno。当mode设置为F_OK时,只要文件存在就会返回0,无论是否有其他权限。
下面是使用access函数判断文件是否存在的示例代码:
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
int main() {
const char *file_path = "./test.txt";
// 使用F_OK模式判断文件是否存在
if (access(file_path, F_OK) == 0) {
printf("文件 %s 存在n", file_path);
} else {
printf("文件 %s 不存在,错误信息:%sn", file_path, strerror(errno));
}
return 0;
}
2. stat函数
stat函数是sys/stat.h头文件中提供的函数,用于获取指定文件的元数据信息,如果文件不存在,函数会调用失败,因此也可以用来判断文件是否存在。它的函数原型如下:
#include <sys/stat.h> #include <unistd.h> int stat(const char *pathname, struct stat *statbuf);
参数说明:
- pathname:需要获取信息的文件路径字符串
- statbuf:指向struct stat结构体的指针,函数会将文件的元数据填充到这个结构体中
返回值:成功返回0,失败返回-1并设置errno。如果文件不存在,errno会被设置为ENOENT。
使用stat函数判断文件是否存在的示例代码如下:
#include <stdio.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
int main() {
const char *file_path = "./test.txt";
struct stat file_stat;
// 调用stat函数获取文件信息
if (stat(file_path, &file_stat) == 0) {
printf("文件 %s 存在n", file_path);
} else {
if (errno == ENOENT) {
printf("文件 %s 不存在n", file_path);
} else {
printf("获取文件信息失败,错误信息:%sn", strerror(errno));
}
}
return 0;
}
3. fopen函数
fopen函数是stdio.h头文件中提供的标准库函数,用于打开指定文件,当以只读模式打开不存在的文件时,函数会返回NULL,因此也可以间接判断文件是否存在。它的函数原型如下:
#include <stdio.h> FILE *fopen(const char *pathname, const char *mode);
参数说明:
- pathname:需要打开的文件路径字符串
- mode:打开文件的模式,比如"r"表示只读模式,"w"表示写入模式(不存在会创建)等
返回值:成功返回文件指针,失败返回NULL并设置errno。
使用fopen函数判断文件是否存在的示例代码如下:
#include <stdio.h>
#include <errno.h>
#include <string.h>
int main() {
const char *file_path = "./test.txt";
// 以只读模式打开文件
FILE *fp = fopen(file_path, "r");
if (fp != NULL) {
printf("文件 %s 存在n", file_path);
fclose(fp);
} else {
printf("文件 %s 不存在,错误信息:%sn", file_path, strerror(errno));
}
return 0;
}
不同函数的选择建议
如果只需要判断文件是否存在,不需要获取其他文件信息,优先使用access函数,它的逻辑更直观,代码更简洁。如果需要同时获取文件的大小、修改时间等元数据,那么使用stat函数更合适,避免重复调用系统函数。如果本身就需要打开文件进行读写操作,那么直接使用fopen函数,根据返回值判断文件是否存在即可,不需要额外调用其他判断函数。
需要注意,判断文件存在和实际操作文件之间可能存在时间差,其他进程可能在这个时间差内删除或者创建文件,因此判断文件存在后操作文件时,依然需要处理操作失败的情况。