I would like to find the fastest way to check if a file exist 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 */
}
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.
Results for total time to run the 100,000 calls averaged over 5 runs,
exists_test0
(ifstream)exists_test1
(FILE fopen)exists_test2
(posix access())exists_test3
(posix stat())The
stat()
function provided the best performance on my system (Linux, compiled withg++
), with a standardfopen
call being your best bet if you for some reason refuse to use POSIX functions.