• 文件和文件夹的一些操作


    • 文件是否存在
    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;
    }
    
  • 相关阅读:
    js中的异常处理
    CSS3之box-sizing属性
    AJAX
    NaN与Null与undefiined的关系
    跳转语句之continue与break
    npm火速上手
    程序里面的‘脑筋急转弯’
    css伪元素::before与::after
    常用正则表达式、JS中的正则以及ES6的扩展
    git
  • 原文地址:https://www.cnblogs.com/sunwenqi/p/15972403.html
Copyright © 2020-2023  润新知