使用std::ifstream打开文件并调用is_open()判断文件是否存在,若成功打开则存在且可读,否则可能不存在或无权限;2. 该方法简单可靠但无法区分文件不存在和权限问题;3. C++17起推荐使用std::filesystem::exists进行精确判断。

在C++中,可以使用
fstream
std::ifstream
通过构造
std::ifstream
is_open()
示例代码:
#include <fstream>
#include <iostream>
bool fileExists(const std::string& filename) {
std::ifstream file(filename);
return file.is_open();
}
int main() {
std::string filename = "test.txt";
if (fileExists(filename)) {
std::cout << "文件存在。\n";
} else {
std::cout << "文件不存在。\n";
}
return 0;
}
这种方法依赖于能否成功打开文件,因此需要注意以下几点:
立即学习“C++免费学习笔记(深入)”;
is_open()
false
如果需要严格区分“文件不存在”和其他错误(如权限、路径无效等),可以结合
<filesystem>
#include <filesystem>
bool fileExists(const std::string& filename) {
return std::filesystem::exists(filename);
}
但若只能使用
fstream
基本上就这些。用
ifstream
以上就是C++如何使用fstream判断文件是否存在的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号