1 #pragma once 2 3 #include <filesystem> 4 #include <utility> 5 6 namespace openpower 7 { 8 namespace pels 9 { 10 namespace util 11 { 12 13 namespace fs = std::filesystem; 14 15 /** 16 * @class TemporaryFile 17 * 18 * A temporary file in the file system. 19 * 20 * The temporary file is created by the constructor. The absolute path to the 21 * file can be obtained using getPath(). 22 * 23 * Note: Callers responsibility to delete the file after usage. 24 * The temporary file can be deleted by calling remove(). 25 * 26 * TemporaryFile objects cannot be copied, but they can be moved. This enables 27 * them to be stored in containers like std::vector. 28 */ 29 class TemporaryFile 30 { 31 public: 32 // Specify which compiler-generated methods we want 33 TemporaryFile(const TemporaryFile&) = delete; 34 TemporaryFile& operator=(const TemporaryFile&) = delete; 35 36 /** 37 * Constructor. 38 * 39 * Creates a temporary file in the temporary directory (normally /tmp). 40 * 41 * Throws an exception if the file cannot be created. 42 * 43 * @param data - data buffer 44 * @param len - length of the data buffer 45 */ 46 TemporaryFile(const char* data, const uint32_t len); 47 48 /** 49 * Move constructor. 50 * 51 * Transfers ownership of a temporary file. 52 * 53 * @param file TemporaryFile object being moved 54 */ TemporaryFile(TemporaryFile && file)55 TemporaryFile(TemporaryFile&& file) : path{std::move(file.path)} 56 { 57 // Clear path in other object; after move path is in unspecified state 58 file.path.clear(); 59 } 60 61 /** 62 * Move assignment operator. 63 * 64 * Deletes the temporary file owned by this object. Then transfers 65 * ownership of the temporary file owned by the other object. 66 * 67 * Throws an exception if an error occurs during the deletion. 68 * 69 * @param file TemporaryFile object being moved 70 */ 71 TemporaryFile& operator=(TemporaryFile&& file); 72 73 /** 74 * Destructor. 75 */ ~TemporaryFile()76 ~TemporaryFile() {} 77 78 /** 79 * Deletes the temporary file. 80 * 81 * Does nothing if the file has already been deleted. 82 * 83 * Throws an exception if an error occurs during the deletion. 84 */ 85 void remove(); 86 87 /** 88 * Returns the absolute path to the temporary file. 89 * 90 * Returns an empty path if the file has been deleted. 91 * 92 * @return temporary file path 93 */ getPath() const94 const fs::path& getPath() const 95 { 96 return path; 97 } 98 getFd() const99 int getFd() const 100 { 101 return fd; 102 } 103 104 private: 105 /** 106 * Absolute path to the temporary file. 107 */ 108 fs::path path{}; 109 110 /** 111 * File descriptor of the temporary file. 112 */ 113 int fd; 114 }; 115 116 } // namespace util 117 } // namespace pels 118 } // namespace openpower 119