blob: 90bf64b64d67f0a53b1756e196ff4de4ce91cc3b [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 Tanouseacbfdd2024-04-04 12:00:24 -07006#include <filesystem>
Ed Tanous73030632022-01-14 10:09:47 -08007#include <iostream>
8#include <stdexcept>
Ed Tanouseacbfdd2024-04-04 12:00:24 -07009#include <string>
Ed Tanous73030632022-01-14 10:09:47 -080010
11FileHandle::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
Patrick Williams2aaf7172024-08-16 15:20:40 -040022FileHandle::FileHandle(int fdIn) : fd(fdIn) {};
Ed Tanous73030632022-01-14 10:09:47 -080023
Ed Tanous2049bd22022-07-09 07:20:26 -070024FileHandle::FileHandle(FileHandle&& in) noexcept : fd(in.fd)
Ed Tanous73030632022-01-14 10:09:47 -080025{
Ed Tanous73030632022-01-14 10:09:47 -080026 in.fd = -1;
27}
28
29FileHandle& FileHandle::operator=(FileHandle&& in) noexcept
30{
31 fd = in.fd;
32 in.fd = -1;
33 return *this;
34}
35
36FileHandle::~FileHandle()
37{
Hao Jiange330c0c2022-09-06 23:59:41 +000038 if (fd >= 0)
Ed Tanous73030632022-01-14 10:09:47 -080039 {
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
Ed Tanous2049bd22022-07-09 07:20:26 -070048int FileHandle::handle() const
Ed Tanous73030632022-01-14 10:09:47 -080049{
50 return fd;
51}