blob: d36911cafa1d0ba38960309f9d81d9c7ada393fb [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
Ed Tanous73030632022-01-14 10:09:47 -08006#include <iostream>
7#include <stdexcept>
8
9FileHandle::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
20FileHandle::FileHandle(int fdIn) : fd(fdIn){};
21
Ed Tanous2049bd22022-07-09 07:20:26 -070022FileHandle::FileHandle(FileHandle&& in) noexcept : fd(in.fd)
Ed Tanous73030632022-01-14 10:09:47 -080023{
Ed Tanous73030632022-01-14 10:09:47 -080024 in.fd = -1;
25}
26
27FileHandle& FileHandle::operator=(FileHandle&& in) noexcept
28{
29 fd = in.fd;
30 in.fd = -1;
31 return *this;
32}
33
34FileHandle::~FileHandle()
35{
Hao Jiange330c0c2022-09-06 23:59:41 +000036 if (fd >= 0)
Ed Tanous73030632022-01-14 10:09:47 -080037 {
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
Ed Tanous2049bd22022-07-09 07:20:26 -070046int FileHandle::handle() const
Ed Tanous73030632022-01-14 10:09:47 -080047{
48 return fd;
49}