优先使用std::filesystem::exists(C++17),其次根据平台选择_access_s或stat函数,也可通过文件流简单判断。

在C++中判断文件或目录是否存在,有多种方法,具体取决于使用的标准和平台。以下是几种常用且有效的方式。
使用 std::filesystem(C++17 及以上)
现代C++推荐使用 std::filesystem 库,它提供了简洁直观的接口来检查文件或目录是否存在。示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <filesystem>
#include <iostream>
<p>int main() {
std::string path = "example.txt";</p><pre class="brush:php;toolbar:false;">if (std::filesystem::exists(path)) {
std::cout << "文件或目录存在\n";
if (std::filesystem::is_regular_file(path)) {
std::cout << "这是一个文件\n";
} else if (std::filesystem::is_directory(path)) {
std::cout << "这是一个目录\n";
}
} else {
std::cout << "不存在\n";
}
return 0;}
编译时需要启用 C++17 支持,例如使用 g++:
g++ -std=c++17 your_file.cpp -o your_file
使用 _access_s 或 _waccess_s(Windows 平台)
在 Windows 上,可以使用 Microsoft 提供的运行时函数 _access_s 来检查文件是否存在及访问权限。示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <io.h>
#include <stdio.h>
<p>int main() {
const char* path = "example.txt";</p><pre class="brush:php;toolbar:false;">if (_access_s(path, 0) == 0) {
printf("文件存在\n");
} else {
printf("文件不存在\n");
}
return 0;}
参数说明:传入 0 表示仅检查是否存在,4 表示只读权限,2 表示写权限,6 表示读写权限。
使用 stat 函数(跨平台,POSIX 兼容)
在类 Unix 系统(包括 Linux 和 macOS)上,可以使用 stat 函数检查文件状态。该方法也可在 Windows 上通过示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <sys/stat.h>
#include <iostream>
<p>bool fileExists(const std::string& path) {
struct stat buffer;
return (stat(path.c_str(), &buffer) == 0);
}</p><p>bool isDirectory(const std::string& path) {
struct stat buffer;
if (stat(path.c_str(), &buffer) != 0) return false;
return S_ISDIR(buffer.st_mode);
}
优点是兼容性较好,适合不支持 C++17 的项目。
尝试打开文件流(简单但有限)
对于普通文件,可以通过 std::ifstream 尝试打开来判断是否存在。示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <fstream>
#include <iostream>
<p>bool fileExists(const std::string& path) {
std::ifstream file(path);
bool exists = file.good();
file.close();
return exists;
}
注意:这种方法只能判断是否能打开文件,不能区分文件和目录,也不适用于无读权限但存在的文件。
基本上就这些常见方式。如果使用现代C++,优先选择 std::filesystem::exists,简洁安全;老旧项目可考虑 stat 或 _access_s。跨平台项目建议封装一层判断逻辑,统一接口。不复杂但容易忽略细节,比如权限、符号链接等特殊情况。











