ScopedTempDir

来源:互联网 发布:淘宝匿名评价不显示吗 编辑:程序博客网 时间:2024/05/14 10:34

class ScopedTempDir {

 public:

  // No directory is owned/created initially.

  ScopedTempDir();

 

  // Recursively delete path_

  ~ScopedTempDir();

 

  // Creates a unique directory in TempPath, and takes ownership of it.

  // See file_util::CreateNewTemporaryDirectory.

  bool CreateUniqueTempDir();

 

  // Takes ownership of directory at |path|, creating it if necessary.

  // Don't call multiple times unless Take() has been called first.

  bool Set(const FilePath& path);

 

  // Caller takes ownership of the temporary directory so it won't be destroyed

  // when this object goes out of scope.

  FilePath Take();

 

  const FilePath& path() const { return path_; }

 

  // Returns true if path_ is non-empty and exists.

  bool IsValid() const;

 

 private:

  FilePath path_;

 

  DISALLOW_COPY_AND_ASSIGN(ScopedTempDir);

};

ScopedTempDir::ScopedTempDir() {
}
ScopedTempDir::~ScopedTempDir() {
  if (!path_.empty() && !file_util::Delete(path_, true))
    LOG(ERROR) << "ScopedTempDir unable to delete " << path_.value();
}
bool ScopedTempDir::CreateUniqueTempDir() {
  // This "scoped_dir" prefix is only used on Windows and serves as a template
  // for the unique name.
  if (!file_util::CreateNewTempDirectory(FILE_PATH_LITERAL("scoped_dir"),
                                         &path_))
    return false;
  return true;
}
bool ScopedTempDir::Set(const FilePath& path) {
  DCHECK(path_.empty());
  if (!file_util::DirectoryExists(path) &&
      !file_util::CreateDirectory(path)) {
    return false;
  }
  path_ = path;
  return true;
}
FilePath ScopedTempDir::Take() {
  FilePath ret = path_;
  path_ = FilePath();
  return ret;
}
bool ScopedTempDir::IsValid() const {
  return !path_.empty() && file_util::DirectoryExists(path_);
}

原创粉丝点击