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

在C++中判断文件或目录是否存在,有多种方法,具体取决于使用的标准和平台。以下是几种常用且有效的方式。
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <filesystem>
#include <iostream>
<p>int main() {
std::string path = "example.txt";</p><pre class="brush:php;toolbar:false;"><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
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <io.h>
#include <stdio.h>
<p>int main() {
const char* path = "example.txt";</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">if (_access_s(path, 0) == 0) {
printf("文件存在\n");
} else {
printf("文件不存在\n");
}
return 0;}
参数说明:传入 0 表示仅检查是否存在,4 表示只读权限,2 表示写权限,6 表示读写权限。
示例代码:
立即学习“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 的项目。
示例代码:
立即学习“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。跨平台项目建议封装一层判断逻辑,统一接口。不复杂但容易忽略细节,比如权限、符号链接等特殊情况。
以上就是c++++中如何判断文件是否存在_C++检查文件或目录存在的方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号