byteme
C++ wrappers for buffered inputs
Loading...
Searching...
No Matches
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 <string>
7#include <cstdio>
8#include "Writer.hpp"
9#include "SelfClosingFILE.hpp"
10
17namespace byteme {
18
25class RawFileWriter : public Writer {
26public:
31 RawFileWriter(const char* path, size_t buffer_size = 65536) : my_file(path, "wb") {
32 if (std::setvbuf(my_file.handle, nullptr, _IOFBF, buffer_size)) {
33 throw std::runtime_error("failed to set a buffer size for file writing");
34 }
35 }
36
41 RawFileWriter(const std::string& path, size_t buffer_size = 65536) : RawFileWriter(path.c_str(), buffer_size) {}
42
43public:
44 using Writer::write;
45
46 void write(const unsigned char* buffer, size_t n) {
47 size_t ok = std::fwrite(buffer, sizeof(unsigned char), n, my_file.handle);
48 if (ok < n) {
49 throw std::runtime_error("failed to write raw binary file (fwrite error " + std::to_string(std::ferror(my_file.handle)) + ")");
50 }
51 }
52
53 void finish() {
54 if (std::fclose(my_file.handle)) {
55 throw std::runtime_error("failed to close raw binary file");
56 }
57 my_file.handle = nullptr;
58 }
59
60private:
61 SelfClosingFILE my_file;
62};
63
64}
65
66#endif
Write to an output sink.
Write bytes to a file.
Definition RawFileWriter.hpp:25
RawFileWriter(const std::string &path, size_t buffer_size=65536)
Definition RawFileWriter.hpp:41
void finish()
Definition RawFileWriter.hpp:53
void write(const unsigned char *buffer, size_t n)
Definition RawFileWriter.hpp:46
RawFileWriter(const char *path, size_t buffer_size=65536)
Definition RawFileWriter.hpp:31
Virtual class for writing bytes to a sink.
Definition Writer.hpp:18
virtual void write(const unsigned char *buffer, size_t n)=0
Simple byte readers and writers.