-
Notifications
You must be signed in to change notification settings - Fork 9
/
file.hpp
82 lines (70 loc) · 1.89 KB
/
file.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#pragma once
#include <stdio.h>
#include <filesystem>
namespace phosphor
{
namespace user
{
/** @class File
* @brief Responsible for handling file pointer
* Needed by putspent(3)
*/
class File
{
private:
/** @brief handler for operating on file */
FILE* fp = NULL;
/** @brief File name. Needed in the case where the temp
* needs to be removed
*/
const std::string& name;
/** @brief Should the file be removed at exit */
bool removeOnExit = false;
public:
File() = delete;
File(const File&) = delete;
File& operator=(const File&) = delete;
File(File&&) = delete;
File& operator=(File&&) = delete;
/** @brief Opens file and uses it to do file operation
*
* @param[in] name - File name
* @param[in] mode - File open mode
* @param[in] removeOnExit - File to be removed at exit or no
*/
File(const std::string& name, const std::string& mode,
bool removeOnExit = false) : name(name), removeOnExit(removeOnExit)
{
fp = fopen(name.c_str(), mode.c_str());
}
/** @brief Opens file using provided file descriptor
*
* @param[in] fd - File descriptor
* @param[in] name - File name
* @param[in] mode - File open mode
* @param[in] removeOnExit - File to be removed at exit or no
*/
File(int fd, const std::string& name, const std::string& mode,
bool removeOnExit = false) : name(name), removeOnExit(removeOnExit)
{
fp = fdopen(fd, mode.c_str());
}
~File()
{
if (fp)
{
fclose(fp);
}
// Needed for exception safety
if (removeOnExit && std::filesystem::exists(name))
{
std::filesystem::remove(name);
}
}
auto operator()()
{
return fp;
}
};
} // namespace user
} // namespace phosphor