c++ - 如何检查文件是否存在于 C++ 中?
问题描述
我想确定 C++ 11 中是否存在文件
我有以下代码:
ifstream inputFile(c);
if (!inputFile.good()) {
std::cout << "No file found" << '\n';
}
和
if (inputFile.peek() == std::ifstream::traits_type::eof()){
....
}
哪一个是正确的和惯用的?
解决方案
在 C++17<filesystem>
中,您可以执行以下操作:
namespace fs = std::filesystem;
fs::path f{ "file.txt" };
if (fs::exists(f)) std::cout << "yes";
else std::cout << "nope";
推荐阅读
- android - 在 android 中打开 Splash scree 之前会延迟 1 到 2 秒
- javascript - 在铯中创建折线时出错
- ios - 无法将 2 行代码从 Swift 转换为 Objective C
- c++ - 将模板化参数包存储在 std::function 对象中
- c++ - 为什么c++ assert() 函数会给程序带来开销
- android - RecyclerView 项目大小在滚动时发生变化
- html - CSS,如何在一段时间后改变背景并保持这样
- android - React Native - 弃用后如何使用 ref?
- bash - 验证 shell 脚本中的字母数字出错了
- java - 在 Spring Boot 中将异常处理添加为 jar,控制器建议不会被调用