blob: 67246986bbe1a30be2e53bdfc102350b81268778 [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
22FileHandle::FileHandle(FileHandle&& in) noexcept
23{
24 fd = in.fd;
25 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{
37 if (fd)
38 {
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
47int FileHandle::handle()
48{
49 return fd;
50}