1 // Copyright 2023 The Chromium Authors 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef BASE_FILES_SCOPED_TEMP_FILE_H_ 6 #define BASE_FILES_SCOPED_TEMP_FILE_H_ 7 8 #include "base/base_export.h" 9 #include "base/files/file_path.h" 10 11 namespace base { 12 13 // An owned FilePath that's deleted when this object goes out of scope. 14 // Deletion is attempted on destruction, but is not guaranteed. 15 class BASE_EXPORT ScopedTempFile { 16 public: 17 // No file is owned/created initially. 18 ScopedTempFile(); 19 20 ScopedTempFile(ScopedTempFile&&) noexcept; 21 ScopedTempFile& operator=(ScopedTempFile&&) noexcept; 22 23 ~ScopedTempFile(); 24 25 // The owned path must be empty before calling Create(). 26 // Returns true on success. 27 [[nodiscard]] bool Create(); 28 29 // Returns true on success or if the file was never created. 30 [[nodiscard]] bool Delete(); 31 32 // Attempts to delete the file. The managed path is reset regardless of 33 // if the deletion was successful. 34 void Reset(); 35 path()36 [[nodiscard]] const base::FilePath& path() const { return path_; } 37 38 // NOLINTNEXTLINE(google-explicit-constructor) 39 operator bool() const { return !path_.empty(); } 40 41 private: 42 FilePath path_; 43 }; 44 45 } // namespace base 46 47 #endif // BASE_FILES_SCOPED_TEMP_FILE_H_ 48