首页 > 解决方案 > 如何检查文件是否存在于 C++ 中?

问题描述

我想确定 C++ 11 中是否存在文件

我有以下代码:

ifstream inputFile(c);

if (!inputFile.good()) {
        std::cout << "No file found" << '\n';           
}

if (inputFile.peek() == std::ifstream::traits_type::eof()){
           ....
}

哪一个是正确的和惯用的?

标签: c++c++11

解决方案


在 C++17<filesystem>中,您可以执行以下操作:

namespace fs = std::filesystem;
fs::path f{ "file.txt" };
if (fs::exists(f)) std::cout << "yes";
else               std::cout << "nope";

推荐阅读