Jayanth Othayoth | 4f7b9bd | 2021-11-25 08:11:12 -0600 | [diff] [blame] | 1 | #pragma once |
| 2 | |
| 3 | #include <filesystem> |
| 4 | #include <utility> |
| 5 | |
| 6 | namespace openpower::util |
| 7 | { |
| 8 | |
| 9 | namespace fs = std::filesystem; |
| 10 | |
| 11 | /** |
| 12 | * @class TemporaryFile |
| 13 | * |
| 14 | * A temporary file in the file system. |
| 15 | * |
| 16 | * The temporary file is created by the constructor. The absolute path to the |
| 17 | * file can be obtained using getPath(). |
| 18 | * |
| 19 | * The temporary file can be deleted by calling remove(). Otherwise the file |
| 20 | * will be deleted by the destructor. |
| 21 | * |
| 22 | */ |
| 23 | class TemporaryFile |
| 24 | { |
| 25 | public: |
| 26 | // Specify which compiler-generated methods we want |
| 27 | TemporaryFile(const TemporaryFile&) = delete; |
| 28 | TemporaryFile(TemporaryFile&&) = delete; |
| 29 | TemporaryFile& operator=(const TemporaryFile&) = delete; |
| 30 | |
| 31 | /** |
| 32 | * Constructor. |
| 33 | * |
| 34 | * Creates a temporary file in the temporary directory (normally /tmp). |
| 35 | * |
| 36 | * Throws an exception if the file cannot be created. |
| 37 | */ |
| 38 | TemporaryFile(); |
| 39 | |
| 40 | /** |
| 41 | * Destructor. |
| 42 | * |
| 43 | * Deletes the temporary file if necessary. |
| 44 | */ |
| 45 | ~TemporaryFile() |
| 46 | { |
| 47 | try |
| 48 | { |
| 49 | remove(); |
| 50 | } |
| 51 | catch (...) |
| 52 | { |
| 53 | // Destructors should not throw exceptions |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | /** |
| 58 | * Deletes the temporary file. |
| 59 | * |
| 60 | * Does nothing if the file has already been deleted. |
| 61 | * |
| 62 | * Log error message if an error occurs during the deletion. |
| 63 | */ |
| 64 | void remove(); |
| 65 | |
| 66 | /** |
| 67 | * Returns the absolute path to the temporary file. |
| 68 | * |
| 69 | * Returns an empty path if the file has been deleted. |
| 70 | * |
| 71 | * @return temporary file path |
| 72 | */ |
| 73 | const fs::path& getPath() const |
| 74 | { |
| 75 | return path; |
| 76 | } |
| 77 | |
| 78 | private: |
| 79 | /** |
| 80 | * Absolute path to the temporary file. |
| 81 | * |
| 82 | * Empty when file has been deleted. |
| 83 | */ |
| 84 | fs::path path{}; |
| 85 | }; |
| 86 | |
| 87 | } // namespace openpower::util |