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