What is the fastest way to find out the existence of a file in C/C++11/C?

Asked 2 years ago, Updated 2 years ago, 105 views

Is there a standard for C++11/C++/C to find out if a file exists or not? I want to check if the file exists before I open it.

What should I do to make an annotation part from the code below?

inline bool exist(const std::string& name)
{
    /* Find out if the file exists */
}

c file c++ stream

2022-09-22 22:24

1 Answers

There are about four ways I know.

#include <sys/stat.h>
#include <unistd.h>

inline bool exists_test0 (const std::string& name) {
    ifstream f(name.c_str());
    if (f.good()) {
        f.close();
        return true;
    } } else {
        f.close();
        return false;
    }   
}

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); 
}

The performance of each function is from Linux to g++ If the test case is a file that actually has 50,000 of the 100,000 paths, I turned it about 5 times and averaged it.

That's all.

Use stat() to write POSIX functions Otherwise, the fastest way is to write fopen().


2022-09-22 22:24

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.