Andrew Jeffery | e73bd0a | 2023-01-25 10:39:57 +1030 | [diff] [blame] | 1 | #include "FileHandle.hpp" |
| 2 | |
Ed Tanous | 7303063 | 2022-01-14 10:09:47 -0800 | [diff] [blame] | 3 | #include <fcntl.h> |
| 4 | #include <unistd.h> |
| 5 | |
Ed Tanous | eacbfdd | 2024-04-04 12:00:24 -0700 | [diff] [blame] | 6 | #include <filesystem> |
Ed Tanous | 7303063 | 2022-01-14 10:09:47 -0800 | [diff] [blame] | 7 | #include <iostream> |
| 8 | #include <stdexcept> |
Ed Tanous | eacbfdd | 2024-04-04 12:00:24 -0700 | [diff] [blame] | 9 | #include <string> |
Ed Tanous | 7303063 | 2022-01-14 10:09:47 -0800 | [diff] [blame] | 10 | |
| 11 | FileHandle::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 Williams | 2aaf717 | 2024-08-16 15:20:40 -0400 | [diff] [blame] | 22 | FileHandle::FileHandle(int fdIn) : fd(fdIn) {}; |
Ed Tanous | 7303063 | 2022-01-14 10:09:47 -0800 | [diff] [blame] | 23 | |
Ed Tanous | 2049bd2 | 2022-07-09 07:20:26 -0700 | [diff] [blame] | 24 | FileHandle::FileHandle(FileHandle&& in) noexcept : fd(in.fd) |
Ed Tanous | 7303063 | 2022-01-14 10:09:47 -0800 | [diff] [blame] | 25 | { |
Ed Tanous | 7303063 | 2022-01-14 10:09:47 -0800 | [diff] [blame] | 26 | in.fd = -1; |
| 27 | } |
| 28 | |
| 29 | FileHandle& FileHandle::operator=(FileHandle&& in) noexcept |
| 30 | { |
| 31 | fd = in.fd; |
| 32 | in.fd = -1; |
| 33 | return *this; |
| 34 | } |
| 35 | |
| 36 | FileHandle::~FileHandle() |
| 37 | { |
Hao Jiang | e330c0c | 2022-09-06 23:59:41 +0000 | [diff] [blame] | 38 | if (fd >= 0) |
Ed Tanous | 7303063 | 2022-01-14 10:09:47 -0800 | [diff] [blame] | 39 | { |
| 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 Tanous | 2049bd2 | 2022-07-09 07:20:26 -0700 | [diff] [blame] | 48 | int FileHandle::handle() const |
Ed Tanous | 7303063 | 2022-01-14 10:09:47 -0800 | [diff] [blame] | 49 | { |
| 50 | return fd; |
| 51 | } |