使用ifstream打开文件流,成功则存在,失败则不存在
#include <sys/stat.h>
#include <unistd.h>
#include <string>
#include <fstream>
inline bool exists_test (const std::string& name) {
ifstream f(name.c_str());
return f.good();
}
以fopen读方式打开文件,成功则存在,否则不存在
#include <sys/stat.h>
#include <unistd.h>
#include <string>
#include <fstream>
inline bool exists_test (const std::string& name) {
if (FILE *file = fopen(name.c_str(), "r")) {
fclose(file);
return true;
} else {
return false;
}
}
使用access函数获取文件状态,成功则存在,否则不存在
#include <sys/stat.h>
#include <unistd.h>
#include <string>
#include <fstream>
inline bool exists_test (const std::string& name) {
return ( access( name.c_str(), F_OK ) != -1 );
}
使用stat函数获取文件状态,成功则存在,否则不存在
#include <sys/stat.h>
#include <unistd.h>
#include <string>
#include <fstream>
inline bool exists_test (const std::string& name) {
struct stat buffer;
return (stat (name.c_str(), &buffer) == 0);
}