I would like to find the fastest way to check if a file exists in standard C++11, 14, 17, or C. I have thousands of files and before doing something on them I need to check if all of them exist. What can I write instead of /* SOMETHING */
in the following function?
inline bool exist(const std::string& name) { /* SOMETHING */ }
access() Function to Check if a File Exists in C Another way to check if the file exists is to use the access() function. The unistd. h header file has a function access to check if the file exists or not. We can use R_OK for reading permission, W_OK for write permission and X_OK to execute permission.
Use ifile. open(): ifile. open() is mainly used to check if a file exists in the specific directory or not.
The FileExists Method (System::SysUtils::FileExists) is a SysUtils Method in C++ Builder that checks whether a specified file exists. FileExists returns True if the file specified by FileName exists. If the file does not exist, FileExists returns False.
C++ program to find a specific file in a directory opendir-It will open directory stream and take a string as a parameter and return pointer of type DIR if it successfully opens directory or returns a NULL pointer if it is not able to open directory. closedir-It will close the directory.
Well I threw together a test program that ran each of these methods 100,000 times, half on files that existed and half on files that didn't.
#include <sys/stat.h> #include <unistd.h> #include <string> #include <fstream> inline bool exists_test0 (const std::string& name) { ifstream f(name.c_str()); return f.good(); } inline bool exists_test1 (const std::string& name) { if (FILE *file = fopen(name.c_str(), "r")) { fclose(file); return true; } else { return false; } } inline bool exists_test2 (const std::string& name) { return ( access( name.c_str(), F_OK ) != -1 ); } inline bool exists_test3 (const std::string& name) { struct stat buffer; return (stat (name.c_str(), &buffer) == 0); }
Results for total time to run the 100,000 calls averaged over 5 runs,
Method | Time |
---|---|
exists_test0 (ifstream) | 0.485s |
exists_test1 (FILE fopen) | 0.302s |
exists_test2 (posix access()) | 0.202s |
exists_test3 (posix stat()) | 0.134s |
The stat()
function provided the best performance on my system (Linux, compiled with g++
), with a standard fopen
call being your best bet if you for some reason refuse to use POSIX functions.
Remark : in C++14 and as soon as the filesystem TS will be finished and adopted, the solution will be to use:
std::experimental::filesystem::exists("helloworld.txt");
and since C++17, only:
std::filesystem::exists("helloworld.txt");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With