xref: /openbmc/dbus-sensors/src/FileHandle.cpp (revision 1d7b4788943d5450e2c72965bb972369ae908b2c)
1 #include "FileHandle.hpp"
2 
3 #include <fcntl.h>
4 #include <unistd.h>
5 
6 #include <iostream>
7 #include <stdexcept>
8 
9 FileHandle::FileHandle(const std::filesystem::path& name,
10                        std::ios_base::openmode mode) :
11     // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg)
12     fd(open(name.c_str(), mode))
13 {
14     if (fd < 0)
15     {
16         throw std::out_of_range(name.string() + " failed to open");
17     }
18 }
19 
20 FileHandle::FileHandle(int fdIn) : fd(fdIn){};
21 
22 FileHandle::FileHandle(FileHandle&& in) noexcept : fd(in.fd)
23 {
24     in.fd = -1;
25 }
26 
27 FileHandle& FileHandle::operator=(FileHandle&& in) noexcept
28 {
29     fd = in.fd;
30     in.fd = -1;
31     return *this;
32 }
33 
34 FileHandle::~FileHandle()
35 {
36     if (fd >= 0)
37     {
38         int r = close(fd);
39         if (r < 0)
40         {
41             std::cerr << "Failed to close fd " << std::to_string(fd);
42         }
43     }
44 }
45 
46 int FileHandle::handle() const
47 {
48     return fd;
49 }
50