blob: 2b6598bd37f88cc46642d2e4913ece17c17198c4 [file] [log] [blame]
Avenash Asai Thambida2cf0d2021-08-26 15:51:47 -05001#include <fcntl.h>
2#include <unistd.h>
3
Willy Tu40553242022-11-14 09:27:39 -08004#include <iostream>
5
Avenash Asai Thambida2cf0d2021-08-26 15:51:47 -05006using namespace std::string_literals;
7std::system_error errnoException(const std::string& message)
8{
9 return std::system_error(errno, std::generic_category(), message);
10}
11
12int 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
22void sysclose(int fd_)
23{
24 close(fd_);
25}
26
27void 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 Tu40553242022-11-14 09:27:39 -080035void readBin(int fd_, size_t offset, void* ptr, size_t size)
Avenash Asai Thambida2cf0d2021-08-26 15:51:47 -050036{
37 lseeker(fd_, offset);
Willy Tu40553242022-11-14 09:27:39 -080038 ssize_t ret = read(fd_, ptr, size);
39 if (ret < 0)
Avenash Asai Thambida2cf0d2021-08-26 15:51:47 -050040 {
41 throw errnoException("Error reading from file"s);
42 }
43}
44
Willy Tu40553242022-11-14 09:27:39 -080045void writeBin(int fd_, size_t offset, void* ptr, size_t size)
Avenash Asai Thambida2cf0d2021-08-26 15:51:47 -050046{
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 Tu40553242022-11-14 09:27:39 -080057 "Tried to send data size "s + std::to_string(size) +
58 " but could only send "s + std::to_string(ret));
Avenash Asai Thambida2cf0d2021-08-26 15:51:47 -050059 }
60}