Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a file exists in C++? [duplicate]

Tags:

c++

c++11

I want to determine if a file exists in C++ 11

I have the following codes:

ifstream inputFile(c);

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

And

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

Which one is correct and idiomatic?

like image 481
nz_21 Avatar asked Mar 03 '23 03:03

nz_21


2 Answers

In C++17 you have <filesystem> in which you can do:

namespace fs = std::filesystem;
fs::path f{ "file.txt" };
if (fs::exists(f)) std::cout << "yes";
else               std::cout << "nope";
like image 87
Andreas DM Avatar answered Mar 12 '23 14:03

Andreas DM


If you're trying to determine if a file exist using C++11 you may want to try this idea

#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;
}
like image 31
Peter Avatar answered Mar 12 '23 12:03

Peter