代码之家  ›  专栏  ›  技术社区  ›  nz_21

如何检查C++中是否存在文件?

  •  0
  • nz_21  · 技术社区  · 6 年前

    我有以下代码:

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

    以及

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

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

    1 回复  |  直到 6 年前
        1
  •  1
  •   Andreas DM    6 年前

    在C++ 17中,你有 <filesystem>

    namespace fs = std::filesystem;
    fs::path f{ "file.txt" };
    if (fs::exists(f)) std::cout << "yes";
    else               std::cout << "nope";
    
        2
  •  0
  •   Peter    6 年前

    如果你想确定一个文件是否存在C++ 11,你可能想试试这个想法。

    #include <iostream>
    #include <fstream>
    
    int main(int argc, char *argv[]){
        std::ifstream file("myfile.txt");
        if(!file.is_open()){
            std::cout << "File not found" << std::endl;
            return -1;
        }
    
        return 0;
    }