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