summaryrefslogtreecommitdiffstats
path: root/file.hpp
blob: ae5cf856e184fdc2e0f3f7113e30ed45fcfd2ff9 (plain)
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
#pragma once

#include <stdio.h>
#include <experimental/filesystem>
namespace phosphor
{
namespace user
{

namespace fs = std::experimental::filesystem;

/** @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());
        }

        ~File()
        {
            if (fp)
            {
                fclose(fp);
            }

            // Needed for exception safety
            if (removeOnExit && fs::exists(name))
            {
                fs::remove(name);
            }
        }

        auto operator()()
        {
            return fp;
        }
};

} // namespace user
} // namespace phosphor
OpenPOWER on IntegriCloud