1 #include <fcntl.h> 2 #include <unistd.h> 3 4 #include <FileHandle.hpp> 5 6 #include <iostream> 7 #include <stdexcept> 8 9 FileHandle::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 20 FileHandle::FileHandle(int fdIn) : fd(fdIn){}; 21 22 FileHandle::FileHandle(FileHandle&& in) noexcept : fd(in.fd) 23 { 24 25 in.fd = -1; 26 } 27 28 FileHandle& FileHandle::operator=(FileHandle&& in) noexcept 29 { 30 fd = in.fd; 31 in.fd = -1; 32 return *this; 33 } 34 35 FileHandle::~FileHandle() 36 { 37 if (fd != 0) 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 47 int FileHandle::handle() const 48 { 49 return fd; 50 } 51