blob: 204cfef8ebe00b431d184c8a42b49c337c5cda9b [file] [log] [blame]
AppaRao Pulib29b5ab2018-05-17 10:28:48 +05301#pragma once
2
3#include <stdio.h>
4
Patrick Williams3d8d7932022-06-16 12:01:28 -05005#include <filesystem>
AppaRao Pulib29b5ab2018-05-17 10:28:48 +05306namespace phosphor
7{
8namespace user
9{
10
Patrick Williams3d8d7932022-06-16 12:01:28 -050011namespace fs = std::filesystem;
AppaRao Pulib29b5ab2018-05-17 10:28:48 +053012
13/** @class File
14 * @brief Responsible for handling file pointer
15 * Needed by putspent(3)
16 */
17class File
18{
19 private:
20 /** @brief handler for operating on file */
21 FILE* fp = NULL;
22
23 /** @brief File name. Needed in the case where the temp
24 * needs to be removed
25 */
26 const std::string& name;
27
28 /** @brief Should the file be removed at exit */
29 bool removeOnExit = false;
30
31 public:
32 File() = delete;
33 File(const File&) = delete;
34 File& operator=(const File&) = delete;
35 File(File&&) = delete;
36 File& operator=(File&&) = delete;
37
38 /** @brief Opens file and uses it to do file operation
39 *
40 * @param[in] name - File name
41 * @param[in] mode - File open mode
42 * @param[in] removeOnExit - File to be removed at exit or no
43 */
44 File(const std::string& name, const std::string& mode,
Patrick Williams1318a5e2024-08-16 15:19:54 -040045 bool removeOnExit = false) : name(name), removeOnExit(removeOnExit)
AppaRao Pulib29b5ab2018-05-17 10:28:48 +053046 {
47 fp = fopen(name.c_str(), mode.c_str());
48 }
49
50 /** @brief Opens file using provided file descriptor
51 *
52 * @param[in] fd - File descriptor
53 * @param[in] name - File name
54 * @param[in] mode - File open mode
55 * @param[in] removeOnExit - File to be removed at exit or no
56 */
57 File(int fd, const std::string& name, const std::string& mode,
Patrick Williams1318a5e2024-08-16 15:19:54 -040058 bool removeOnExit = false) : name(name), removeOnExit(removeOnExit)
AppaRao Pulib29b5ab2018-05-17 10:28:48 +053059 {
60 fp = fdopen(fd, mode.c_str());
61 }
62
63 ~File()
64 {
65 if (fp)
66 {
67 fclose(fp);
68 }
69
70 // Needed for exception safety
71 if (removeOnExit && fs::exists(name))
72 {
73 fs::remove(name);
74 }
75 }
76
77 auto operator()()
78 {
79 return fp;
80 }
81};
82
83} // namespace user
84} // namespace phosphor