
在C++中判断文件或文件夹是否存在,有多种实现方式,取决于你使用的标准和平台。以下是几种常用且跨平台或标准支持的方法。
示例代码:
#include <filesystem>namespace fs = std::filesystem;
bool fileExists(const std::string& path) {
return fs::exists(path);
}
bool isDirectory(const std::string& path) {
return fs::is_directory(path);
}
int main() {
std::string filepath = "test.txt";
std::string dirpath = "my_folder";
if (fileExists(filepath)) {
std::cout << filepath << " 存在\n";
} else {
std::cout << filepath << " 不存在\n";
}
if (isDirectory(dirpath)) {
std::cout << dirpath << " 是一个目录\n";
}
return 0;
}
编译时需要启用 C++17:g++ -std=c++17 your_file.cpp -o your_program
立即学习“C++免费学习笔记(深入)”;
示例代码:
#include <unistd.h>bool fileExists(const std::string& path) {
return access(path.c_str(), F_OK) == 0;
}
注意:access() 在 Windows 上不可靠或不推荐使用,建议仅用于 Unix-like 系统。
示例代码:
#include <cstdio>bool fileExists(const std::string& path) {
FILE* fp = fopen(path.c_str(), "r");
if (fp != nullptr) {
fclose(fp);
return true;
}
return false;
}
这种方法兼容所有平台,但只适用于文件,不能直接判断目录是否存在。
示例代码:
#include <windows.h>bool fileExists(const std::string& path) {
DWORD attr = GetFileAttributesA(path.c_str());
return (attr != INVALID_FILE_ATTRIBUTES);
}
bool isDirectory(const std::string& path) {
DWORD attr = GetFileAttributesA(path.c_str());
if (attr == INVALID_FILE_ATTRIBUTES) return false;
return (attr & FILE_ATTRIBUTE_DIRECTORY);
}
此方法适用于 Windows,需链接 kernel32.lib(通常自动包含)。
基本上就这些。如果你使用的是现代 C++,优先选择 std::filesystem;若需兼容老标准或特定平台,可选用对应方法。关键是根据项目环境选择合适方案。
以上就是c++++怎么判断文件是否存在_C++检查文件或文件夹存在与否的实现的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号