Skip to content Skip to footer

C/C++ 检查一个文件是否存在

1、使用 fopen()简单且通用,适用于所有支持 C 标准库的平台。

#include

int file_exists(const char *filename) {

FILE *file = fopen(filename, "r");

if (file) {

fclose(file);

return 1; // 文件存在

}

return 0; // 文件不存在

}

int main() {

const char *filename = "example.txt";

if (file_exists(filename)) {

printf("文件存在\n");

} else {

printf("文件不存在\n");

}

return 0;

}

2、使用 stat()(C/C++ 都支持) C 和 C++ 中,可以使用 stat 函数来检查一个文件是否存在。这个函数位于 头文件中,它用于获取文件的状态信息。通过检查 stat 函数的返回值,可以判断文件是否存在。比较简单且适用于大多数 Unix-like 系统,也可以在 Windows 上使用,只要包含相应的头文件和库。

#include

#include

int file_exists(const char *filename) {

struct stat buffer;

return (stat(filename, &buffer) == 0); // 如果文件存在,stat 返回 0

}

int main() {

const char *filename = "example.txt";

if (file_exists(filename)) {

printf("文件存在\n");

} else {

printf("文件不存在\n");

}

return 0;

}

3、C++17 方式(标准库方式)C++17 中,标准库引入了 模块,这为文件和目录的操作提供了一套现代且安全的接口。

#include

#include

namespace fs = std::filesystem;

bool file_exists(const std::string& filename) {

return fs::exists(filename);

}

int main() {

std::string filename = "example.txt";

if (file_exists(filename)) {

std::cout << "文件存在" << std::endl;

} else {

std::cout << "文件不存在" << std::endl;

}

return 0;

}

4、C++14/11/98 可用的兼容方式对于那些不支持 C++17 或 的旧版 C++ 环境,使用 std::ifstream 来检查文件是否存在是一个很好的兼容方案。这种方法利用了标准库中的文件流对象(std::ifstream),它会尝试打开指定的文件,如果文件可以被打开,那么该文件必然存在。

#include

#include

bool file_exists(const std::string& filename) {

std::ifstream file(filename);

return file.good(); // 如果文件存在并且无错误,返回 true

}

int main() {

std::string filename = "example.txt";

if (file_exists(filename)) {

std::cout << "文件存在" << std::endl;

} else {

std::cout << "文件不存在" << std::endl;

}

return 0;

}