
在C++中判断一个文件是否存在,有多种方法,根据使用的标准和平台不同,可以选择合适的方式。下面介绍几种常用且跨平台或标准支持的实现方式。
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <filesystem>
int main() {
std::string filename = "test.txt";
if (std::filesystem::exists(filename)) {
std::cout << "文件存在\n";
} else {
std::cout << "文件不存在\n";
}
return 0;
}
说明:
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <fstream>
bool fileExists(const std::string& filename) {
std::ifstream file(filename);
return file.good(); // 文件可打开即认为存在
}
int main() {
if (fileExists("test.txt")) {
std::cout << "文件存在\n";
} else {
std::cout << "文件不存在\n";
}
return 0;
}
注意点:
示例代码:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <unistd.h>
bool fileExists(const std::string& filename) {
return access(filename.c_str(), F_OK) == 0;
}
int main() {
if (fileExists("test.txt")) {
std::cout << "文件存在\n";
} else {
std::cout << "文件不存在\n";
}
return 0;
}
说明:
例如封装一个兼容函数:
#include <fstream>
#include <string>
bool fileExists(const std::string& filename) {
std::ifstream file(filename);
return file.is_open();
}
此方法在 Windows 和 Unix 系统上都能正常工作,适合大多数场景。
基本上就这些。选择哪种方式取决于你的编译环境和项目要求。C++17 的 filesystem 是未来趋势,推荐新项目使用。旧项目可用 ifstream 方案,简单可靠。
以上就是c++++怎么判断一个文件是否存在_c++文件系统检测方法详解的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号