byteme
C++ wrappers for buffered inputs
All Classes Namespaces Files Functions Variables Pages
RawFileWriter.hpp
Go to the documentation of this file.
1#ifndef BYTEME_RAW_FILE_WRITER_HPP
2#define BYTEME_RAW_FILE_WRITER_HPP
3
4#include <vector>
5#include <stdexcept>
6#include <cstdio>
7#include <cstddef>
8#include <optional>
9
10#include "Writer.hpp"
11#include "SelfClosingFILE.hpp"
12
19namespace byteme {
20
30 std::optional<std::size_t> bufsiz;
31};
32
39class RawFileWriter final : public Writer {
40public:
45 RawFileWriter(const char* path, const RawFileWriterOptions& options) : my_file(path, "wb") {
46 set_optional_bufsiz(my_file, options.bufsiz);
47 }
48
49public:
50 using Writer::write;
51
52 void write(const unsigned char* buffer, std::size_t n) {
53 std::size_t ok = std::fwrite(buffer, sizeof(unsigned char), n, my_file.handle);
54 if (ok < n) {
55 throw std::runtime_error("failed to write raw binary file (fwrite error " + std::to_string(std::ferror(my_file.handle)) + ")");
56 }
57 }
58
59 void finish() {
60 if (std::fclose(my_file.handle)) {
61 throw std::runtime_error("failed to close raw binary file");
62 }
63 my_file.handle = nullptr;
64 }
65
66private:
67 SelfClosingFILE my_file;
68};
69
70}
71
72#endif
Write to an output sink.
Write bytes to a file.
Definition RawFileWriter.hpp:39
void finish()
Definition RawFileWriter.hpp:59
RawFileWriter(const char *path, const RawFileWriterOptions &options)
Definition RawFileWriter.hpp:45
void write(const unsigned char *buffer, std::size_t n)
Definition RawFileWriter.hpp:52
Virtual class for writing bytes to a sink.
Definition Writer.hpp:21
virtual void write(const unsigned char *buffer, std::size_t n)=0
Simple byte readers and writers.
Options for the RawFileWriter constructor.
Definition RawFileWriter.hpp:24
std::optional< std::size_t > bufsiz
Definition RawFileWriter.hpp:30