Avatar ·

How to quickly check if a file exists in C++ (C++11/14/17)?

Hi everyone! I've been writing in C++ for about a year, but I still can't find an unequivocally best way to check if a file exists on disk. The problem is that I need to do this very often — I process hundreds of files in a loop, and every millisecond counts. Currently I use this code:

#include <fstream>
bool fileExists(const std::string& filename) {
    std::ifstream f(filename.c_str());
    return f.good();
}
It works, but I suspect this is not the fastest option because it opens the entire file. I also tried using `stat()`:

#include <sys/stat.h>
bool fileExists(const std::string& name) {
    struct stat buffer;
    return (stat(name.c_str(), &buffer) == 0);
}
But this is platform