1 #include "temporary_file.hpp" 2 3 #include <fmt/format.h> 4 #include <unistd.h> 5 6 #include <phosphor-logging/elog-errors.hpp> 7 8 #include <cerrno> 9 #include <cstdlib> 10 #include <stdexcept> 11 #include <string> 12 13 namespace openpower::util 14 { 15 using namespace phosphor::logging; 16 17 TemporaryFile::TemporaryFile() 18 { 19 // Build template path required by mkstemp() 20 std::string templatePath = fs::temp_directory_path() / 21 "openpower-proc-control-XXXXXX"; 22 23 // Generate unique file name, create file, and open it. The XXXXXX 24 // characters are replaced by mkstemp() to make the file name unique. 25 int fd = mkstemp(templatePath.data()); 26 if (fd == -1) 27 { 28 throw std::runtime_error{ 29 std::string{"Unable to create temporary file: "} + strerror(errno)}; 30 } 31 32 // Store path to temporary file 33 path = templatePath; 34 35 // Close file descriptor 36 if (close(fd) == -1) 37 { 38 // Save errno value; will likely change when we delete temporary file 39 int savedErrno = errno; 40 41 // Delete temporary file. The destructor won't be called because 42 // the exception below causes this constructor to exit without 43 // completing. 44 remove(); 45 46 throw std::runtime_error{ 47 std::string{"Unable to close temporary file: "} + 48 strerror(savedErrno)}; 49 } 50 } 51 52 void TemporaryFile::remove() 53 { 54 if (!path.empty()) 55 { 56 // Delete temporary file from file system 57 fs::remove(path); 58 59 // Clear path to indicate file has been deleted 60 path.clear(); 61 } 62 } 63 64 } // namespace openpower::util 65