bool PathExists(const std::string &path) {
struct stat info;
return stat(path.c_str(), &info) == 0;
}
bool DirectoryExists(const std::string &directory_path) {
struct stat info;
return stat(directory_path.c_str(), &info) == 0 && (info.st_mode & S_IFDIR);
}
bool CopyFile(const std::string &from, const std::string &to) {
std::ifstream src(from, std::ios::binary);
if (!src) {
return false;
}
std::ofstream dst(to, std::ios::binary);
if (!dst) {
return false;
}
dst << src.rdbuf();
return true;
}
// file type: file or directory
enum FileType { TYPE_FILE, TYPE_DIR };
bool GetType(const string &filename, FileType *type) {
struct stat stat_buf;
if (lstat(filename.c_str(), &stat_buf) != 0) {
return false;
}
if (S_ISDIR(stat_buf.st_mode) != 0) {
*type = TYPE_DIR;
} else if (S_ISREG(stat_buf.st_mode) != 0) {
*type = TYPE_FILE;
} else {
return false;
}
return true;
}
bool CreateDir(const string &dir) {
int ret = mkdir(dir.c_str(), S_IRWXU | S_IRWXG | S_IRWXO);
if (ret != 0) {
return false;
}
return true;
}
bool DeleteFile(const string &filename) {
if (!PathExists(filename)) {
return true;
}
FileType type;
if (!GetType(filename, &type)) {
return false;
}
if (type == TYPE_FILE) {
if (remove(filename.c_str()) != 0) {
return false;
}
return true;
}
return false;
}