1. 程式人生 > 其它 >檔案和資料夾的一些操作

檔案和資料夾的一些操作

檔案和資料夾的一些操作
  • 檔案是否存在
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;
}