1#include <sys/stat.h>
2#include <unistd.h>
3#include <string>
4#include <fstream>
5
6inline bool exists_test0 (const std::string& name) {
7 ifstream f(name.c_str());
8 return f.good();
9}
10
11inline bool exists_test1 (const std::string& name) {
12 if (FILE *file = fopen(name.c_str(), "r")) {
13 fclose(file);
14 return true;
15 } else {
16 return false;
17 }
18}
19
20inline bool exists_test2 (const std::string& name) {
21 return ( access( name.c_str(), F_OK ) != -1 );
22}
23
24inline bool exists_test3 (const std::string& name) {
25 struct stat buffer;
26 return (stat (name.c_str(), &buffer) == 0);
27}
28
1#include <fstream>
2#include<iostream>
3using namespace std;
4int main() {
5 /* try to open file to read */
6 ifstream ifile;
7 ifile.open("b.txt");
8 if(ifile) {
9 cout<<"file exists";
10 } else {
11 cout<<"file doesn't exist";
12 }
13}
1Method exists_test0 (ifstream): **0.485s**
2Method exists_test1 (FILE fopen): **0.302s**
3Method exists_test2 (posix access()): **0.202s**
4Method exists_test3 (posix stat()): **0.134s**
5