Skip to content

Instantly share code, notes, and snippets.

@samuelsmal
Created October 6, 2014 11:24
Show Gist options
  • Save samuelsmal/762525dfb078b853c2be to your computer and use it in GitHub Desktop.
Save samuelsmal/762525dfb078b853c2be to your computer and use it in GitHub Desktop.
Check if a file exists
#include <sys/stat.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);
}
Method exists_test0 (ifstream): **0.485s**
Method exists_test1 (FILE fopen): **0.302s**
Method exists_test2 (posix access()): **0.202s**
Method exists_test3 (posix stat()): **0.134s**
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment