blob: 76c9e6aa0f74411d432cb6aee2efb70451cd6d6a [file] [log] [blame]
Jayanth Othayothbf54cbb2021-06-03 04:36:48 -05001#pragma once
2
3#include <filesystem>
4#include <utility>
5
6namespace openpower
7{
8namespace pels
9{
10namespace util
11{
12
13namespace 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 */
29class 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 */
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 */
76 ~TemporaryFile()
77 {
78 }
79
80 /**
81 * Deletes the temporary file.
82 *
83 * Does nothing if the file has already been deleted.
84 *
85 * Throws an exception if an error occurs during the deletion.
86 */
87 void remove();
88
89 /**
90 * Returns the absolute path to the temporary file.
91 *
92 * Returns an empty path if the file has been deleted.
93 *
94 * @return temporary file path
95 */
96 const fs::path& getPath() const
97 {
98 return path;
99 }
100
101 int getFd() const
102 {
103 return fd;
104 }
105
106 private:
107 /**
108 * Absolute path to the temporary file.
109 */
110 fs::path path{};
111
112 /**
113 * File descriptor of the temporary file.
114 */
115 int fd;
116};
117
118} // namespace util
119} // namespace pels
120} // namespace openpower