xref: /openbmc/phosphor-host-ipmid/user_channel/file.hpp (revision a6fb32d899c7b6c19201fc0d4ab7417a47958e33)
1 #pragma once
2 
3 #include <stdio.h>
4 
5 #include <filesystem>
6 namespace phosphor
7 {
8 namespace user
9 {
10 
11 namespace fs = std::filesystem;
12 
13 /** @class File
14  *  @brief Responsible for handling file pointer
15  *  Needed by putspent(3)
16  */
17 class File
18 {
19   private:
20     /** @brief handler for operating on file */
21     FILE* fp = nullptr;
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      */
File(const std::string & name,const std::string & mode,bool removeOnExit=false)44     File(const std::string& name, const std::string& mode,
45          bool removeOnExit = false) : name(name), removeOnExit(removeOnExit)
46     {
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      */
File(int fd,const std::string & name,const std::string & mode,bool removeOnExit=false)57     File(int fd, const std::string& name, const std::string& mode,
58          bool removeOnExit = false) : name(name), removeOnExit(removeOnExit)
59     {
60         fp = fdopen(fd, mode.c_str());
61     }
62 
~File()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 
operator ()()77     auto operator()()
78     {
79         return fp;
80     }
81 };
82 
83 } // namespace user
84 } // namespace phosphor
85