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 <string>
7#include <cstdio>
8#include "Reader.hpp"
9#include "SelfClosingFILE.hpp"
10
17namespace byteme {
18
25class RawFileReader : public Reader {
26public:
31 RawFileReader(const char* path, size_t buffer_size = 65536) : my_file(path, "rb"), my_buffer(buffer_size) {}
32
37 RawFileReader(const std::string& path, size_t buffer_size = 65536) : RawFileReader(path.c_str(), buffer_size) {}
38
39public:
40 bool load() {
41 if (!my_okay) {
42 return false;
43 }
44
45 auto& handle = my_file.handle;
46 my_read = std::fread(my_buffer.data(), sizeof(unsigned char), my_buffer.size(), handle);
47
48 if (my_read < my_buffer.size()) {
49 if (std::feof(handle)) {
50 my_okay = false;
51 } else {
52 throw std::runtime_error("failed to read raw binary file (fread error " + std::to_string(std::ferror(handle)) + ")");
53 }
54 }
55
56 return true;
57 }
58
59 const unsigned char* buffer() const {
60 return my_buffer.data();
61 }
62
63 size_t available() const {
64 return my_read;
65 }
66
67private:
68 SelfClosingFILE my_file;
69 std::vector<unsigned char> my_buffer;
70 size_t my_read = 0;
71 bool my_okay = true;
72};
73
74}
75
76#endif
Read an input source.
Read bytes from a file, usually text.
Definition RawFileReader.hpp:25
RawFileReader(const char *path, size_t buffer_size=65536)
Definition RawFileReader.hpp:31
RawFileReader(const std::string &path, size_t buffer_size=65536)
Definition RawFileReader.hpp:37
bool load()
Definition RawFileReader.hpp:40
size_t available() const
Definition RawFileReader.hpp:63
const unsigned char * buffer() const
Definition RawFileReader.hpp:59
Virtual class for reading bytes from a source.
Definition Reader.hpp:15
Simple byte readers and writers.