C/C++ 判断文件是否存在
代码
#include <sys/stat.h>
#include <unistd.h>
#include <string>
#include <fstream>
inline bool exists_ifstream (const std::string& name) {
std::ifstream fin(name.c_str());
return f.good();
}
inline bool exists_fopen (const std::string& name) {
if (FILE *file = fopen(name.c_str(), "r")) {
fclose(file);
return true;
}
return false;
}
inline bool exists_access (const std::string& name) {
return ( access( name.c_str(), F_OK ) != -1 );
}
inline bool exists_stat (const std::string& name) {
struct stat buffer;
return (stat (name.c_str(), &buffer) == 0);
}
在参考资料的评测中,stat
的性能最好。