Avenash Asai Thambi | da2cf0d | 2021-08-26 15:51:47 -0500 | [diff] [blame] | 1 | #include <fcntl.h> |
| 2 | #include <unistd.h> |
| 3 | |
Willy Tu | 4055324 | 2022-11-14 09:27:39 -0800 | [diff] [blame] | 4 | #include <iostream> |
| 5 | |
Avenash Asai Thambi | da2cf0d | 2021-08-26 15:51:47 -0500 | [diff] [blame] | 6 | using namespace std::string_literals; |
| 7 | std::system_error errnoException(const std::string& message) |
| 8 | { |
| 9 | return std::system_error(errno, std::generic_category(), message); |
| 10 | } |
| 11 | |
| 12 | int sysopen(const std::string& path) |
| 13 | { |
| 14 | int fd_ = open(path.c_str(), O_RDWR); |
| 15 | if (fd_ < 0) |
| 16 | { |
| 17 | throw errnoException("Error opening file "s + path); |
| 18 | } |
| 19 | return fd_; |
| 20 | } |
| 21 | |
| 22 | void sysclose(int fd_) |
| 23 | { |
| 24 | close(fd_); |
| 25 | } |
| 26 | |
| 27 | void lseeker(int fd_, size_t offset) |
| 28 | { |
| 29 | if (lseek(fd_, offset, SEEK_SET) < 0) |
| 30 | { |
| 31 | throw errnoException("Cannot lseek to pos "s + std::to_string(offset)); |
| 32 | } |
| 33 | } |
| 34 | |
Willy Tu | 4055324 | 2022-11-14 09:27:39 -0800 | [diff] [blame] | 35 | void readBin(int fd_, size_t offset, void* ptr, size_t size) |
Avenash Asai Thambi | da2cf0d | 2021-08-26 15:51:47 -0500 | [diff] [blame] | 36 | { |
| 37 | lseeker(fd_, offset); |
Willy Tu | 4055324 | 2022-11-14 09:27:39 -0800 | [diff] [blame] | 38 | ssize_t ret = read(fd_, ptr, size); |
| 39 | if (ret < 0) |
Avenash Asai Thambi | da2cf0d | 2021-08-26 15:51:47 -0500 | [diff] [blame] | 40 | { |
| 41 | throw errnoException("Error reading from file"s); |
| 42 | } |
| 43 | } |
| 44 | |
Willy Tu | 4055324 | 2022-11-14 09:27:39 -0800 | [diff] [blame] | 45 | void writeBin(int fd_, size_t offset, void* ptr, size_t size) |
Avenash Asai Thambi | da2cf0d | 2021-08-26 15:51:47 -0500 | [diff] [blame] | 46 | { |
| 47 | lseeker(fd_, offset); |
| 48 | ssize_t ret; |
| 49 | ret = write(fd_, ptr, size); |
| 50 | if (ret < 0) |
| 51 | { |
| 52 | throw errnoException("Error writing to file"s); |
| 53 | } |
| 54 | if (static_cast<size_t>(ret) != size) |
| 55 | { |
| 56 | throw std::runtime_error( |
Willy Tu | 4055324 | 2022-11-14 09:27:39 -0800 | [diff] [blame] | 57 | "Tried to send data size "s + std::to_string(size) + |
| 58 | " but could only send "s + std::to_string(ret)); |
Avenash Asai Thambi | da2cf0d | 2021-08-26 15:51:47 -0500 | [diff] [blame] | 59 | } |
| 60 | } |