blob: af32192aa0d34bd6954cb7771b7322d0a5a18e1d [file] [log] [blame]
Ed Tanous73030632022-01-14 10:09:47 -08001#include <fcntl.h>
2#include <unistd.h>
3
4#include <FileHandle.hpp>
5
6#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}