blob: 227ce231800bd7fd2d07d25a4dc6b09bb740abe2 [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 Tanous2049bd22022-07-09 07:20:26 -070024
Ed Tanous73030632022-01-14 10:09:47 -080025 in.fd = -1;
26}
27
28FileHandle& FileHandle::operator=(FileHandle&& in) noexcept
29{
30 fd = in.fd;
31 in.fd = -1;
32 return *this;
33}
34
35FileHandle::~FileHandle()
36{
Hao Jiange330c0c2022-09-06 23:59:41 +000037 if (fd >= 0)
Ed Tanous73030632022-01-14 10:09:47 -080038 {
39 int r = close(fd);
40 if (r < 0)
41 {
42 std::cerr << "Failed to close fd " << std::to_string(fd);
43 }
44 }
45}
46
Ed Tanous2049bd22022-07-09 07:20:26 -070047int FileHandle::handle() const
Ed Tanous73030632022-01-14 10:09:47 -080048{
49 return fd;
50}