blob: 277a062f5780e607b60884fd024589b7850615db [file] [log] [blame]
Andrew Jefferye73bd0a2023-01-25 10:39:57 +10301#include "FileHandle.hpp"
2
Ed Tanous73030632022-01-14 10:09:47 -08003#include <fcntl.h>
4#include <unistd.h>
5
George Liu61984352025-02-24 14:47:34 +08006#include <phosphor-logging/lg2.hpp>
7
Ed Tanouseacbfdd2024-04-04 12:00:24 -07008#include <filesystem>
Ed Tanous73030632022-01-14 10:09:47 -08009#include <iostream>
10#include <stdexcept>
11
12FileHandle::FileHandle(const std::filesystem::path& name,
13 std::ios_base::openmode mode) :
14 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-vararg)
15 fd(open(name.c_str(), mode))
16{
17 if (fd < 0)
18 {
19 throw std::out_of_range(name.string() + " failed to open");
20 }
21}
22
Patrick Williams2aaf7172024-08-16 15:20:40 -040023FileHandle::FileHandle(int fdIn) : fd(fdIn) {};
Ed Tanous73030632022-01-14 10:09:47 -080024
Ed Tanous2049bd22022-07-09 07:20:26 -070025FileHandle::FileHandle(FileHandle&& in) noexcept : fd(in.fd)
Ed Tanous73030632022-01-14 10:09:47 -080026{
Ed Tanous73030632022-01-14 10:09:47 -080027 in.fd = -1;
28}
29
30FileHandle& FileHandle::operator=(FileHandle&& in) noexcept
31{
32 fd = in.fd;
33 in.fd = -1;
34 return *this;
35}
36
37FileHandle::~FileHandle()
38{
Hao Jiange330c0c2022-09-06 23:59:41 +000039 if (fd >= 0)
Ed Tanous73030632022-01-14 10:09:47 -080040 {
41 int r = close(fd);
42 if (r < 0)
43 {
George Liu61984352025-02-24 14:47:34 +080044 lg2::error("Failed to close fd: '{FD}'", "FD", fd);
Ed Tanous73030632022-01-14 10:09:47 -080045 }
46 }
47}
48
Ed Tanous2049bd22022-07-09 07:20:26 -070049int FileHandle::handle() const
Ed Tanous73030632022-01-14 10:09:47 -080050{
51 return fd;
52}