byteme
C++ wrappers for buffered inputs
Loading...
Searching...
No Matches
RawFileReader.hpp
Go to the documentation of this file.
1#ifndef BYTEME_RAW_FILE_READER_HPP
2#define BYTEME_RAW_FILE_READER_HPP
3
4#include <vector>
5#include <stdexcept>
6#include <cstdio>
7#include <cstddef>
8#include <optional>
9
10#include "Reader.hpp"
11#include "SelfClosingFILE.hpp"
12#include "check_buffer_size.hpp"
13
20namespace byteme {
21
30 std::size_t buffer_size = 65536;
31
37 std::optional<unsigned> bufsiz;
38};
39
46class RawFileReader final : public Reader {
47public:
52 RawFileReader(const char* path, const RawFileReaderOptions& options) :
53 my_file(path, "rb"),
54 my_buffer(check_buffer_size(options.buffer_size))
55 {
56 set_optional_bufsiz(my_file, options.bufsiz);
57 }
58
59public:
60 bool load() {
61 if (!my_okay) {
62 return false;
63 }
64
65 auto& handle = my_file.handle;
66 my_read = std::fread(my_buffer.data(), sizeof(unsigned char), my_buffer.size(), handle);
67
68 if (my_read < my_buffer.size()) {
69 if (std::feof(handle)) {
70 my_okay = false;
71 } else {
72 throw std::runtime_error("failed to read raw binary file (fread error " + std::to_string(std::ferror(handle)) + ")");
73 }
74 }
75
76 return true;
77 }
78
79 const unsigned char* buffer() const {
80 return my_buffer.data();
81 }
82
83 std::size_t available() const {
84 return my_read;
85 }
86
87private:
88 SelfClosingFILE my_file;
89 std::vector<unsigned char> my_buffer;
90 std::size_t my_read = 0;
91 bool my_okay = true;
92};
93
94}
95
96#endif
Read an input source.
Read bytes from a file, usually text.
Definition RawFileReader.hpp:46
bool load()
Definition RawFileReader.hpp:60
RawFileReader(const char *path, const RawFileReaderOptions &options)
Definition RawFileReader.hpp:52
std::size_t available() const
Definition RawFileReader.hpp:83
const unsigned char * buffer() const
Definition RawFileReader.hpp:79
Virtual class for reading bytes from a source.
Definition Reader.hpp:17
Simple byte readers and writers.
Options for the RawFileReader constructor.
Definition RawFileReader.hpp:25
std::optional< unsigned > bufsiz
Definition RawFileReader.hpp:37
std::size_t buffer_size
Definition RawFileReader.hpp:30