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