blob: 8405234d214ccd3183f0d5c7b5b226555cf0d41e [file] [log] [blame]
Jayanth Othayothbf54cbb2021-06-03 04:36:48 -05001#include "temporary_file.hpp"
2
3#include <errno.h>
4#include <fcntl.h>
5#include <stdlib.h>
6#include <string.h>
7#include <unistd.h>
8
9#include <stdexcept>
10
11namespace openpower
12{
13namespace pels
14{
15namespace util
16{
17
18TemporaryFile::TemporaryFile(const char* data, const uint32_t len)
19{
20 // Build template path required by mkstemp()
Patrick Williams075c7922024-08-16 15:19:49 -040021 std::string templatePath =
22 fs::temp_directory_path() / "phosphor-logging-XXXXXX";
Jayanth Othayothbf54cbb2021-06-03 04:36:48 -050023
24 // Generate unique file name, create file, and open it. The XXXXXX
25 // characters are replaced by mkstemp() to make the file name unique.
26 fd = mkostemp(templatePath.data(), O_RDWR);
27 if (fd == -1)
28 {
29 throw std::runtime_error{
30 std::string{"Unable to create temporary file: "} + strerror(errno)};
31 }
32
33 // Update file with input Buffer data
34 auto rc = write(fd, data, len);
35 if (rc == -1)
36 {
37 // Delete temporary file. The destructor won't be called because the
38 // exception below causes this constructor to exit without completing.
39 remove();
Patrick Williams075c7922024-08-16 15:19:49 -040040 throw std::runtime_error{
41 std::string{"Unable to update file: "} + strerror(errno)};
Jayanth Othayothbf54cbb2021-06-03 04:36:48 -050042 }
43
44 // Store path to temporary file
45 path = templatePath;
46}
47
48TemporaryFile& TemporaryFile::operator=(TemporaryFile&& file)
49{
50 // Verify not assigning object to itself (a = std::move(a))
51 if (this != &file)
52 {
53 // Delete temporary file owned by this object
54 remove();
55
56 // Move temporary file path from other object, transferring ownership
57 path = std::move(file.path);
58
59 // Clear path in other object; after move path is in unspecified state
60 file.path.clear();
61 }
62 return *this;
63}
64
65void TemporaryFile::remove()
66{
67 if (!path.empty())
68 {
69 // Delete temporary file from file system
70 fs::remove(path);
71
72 // Clear path to indicate file has been deleted
73 path.clear();
74 }
75}
76
77} // namespace util
78} // namespace pels
79} // namespace openpower