blob: 635273630c4f145d784fe419e84f131f62d7cddd [file] [log] [blame]
Jayanth Othayoth4f7b9bd2021-11-25 08:11:12 -06001#include "temporary_file.hpp"
2
Jayanth Othayoth4f7b9bd2021-11-25 08:11:12 -06003#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
12namespace openpower::util
13{
14using namespace phosphor::logging;
15
16TemporaryFile::TemporaryFile()
17{
18 // Build template path required by mkstemp()
Patrick Williams00dd33e2023-05-10 07:50:37 -050019 std::string templatePath = fs::temp_directory_path() /
20 "openpower-proc-control-XXXXXX";
Jayanth Othayoth4f7b9bd2021-11-25 08:11:12 -060021
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
51void 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