cpp-msgpack-light 0.3.0
A light library to serialize MessagePack.
Loading...
Searching...
No Matches
file_output_stream.h
Go to the documentation of this file.
1/*
2 * Copyright 2024 MusicScience37 (Kenta Kabashima)
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
20#pragma once
21
22#include <cstdio>
23#include <stdexcept>
24#include <string>
25
27
28namespace msgpack_light {
29
33class file_output_stream final : public output_stream {
34public:
40 explicit file_output_stream(const char* file_path)
41 : file_(std::fopen(file_path, "wb")) {
42 if (file_ == nullptr) {
43 throw std::runtime_error(
44 std::string("Failed to open ") + file_path);
45 }
46 }
47
53 explicit file_output_stream(const std::string& file_path)
54 : file_output_stream(file_path.c_str()) {}
55
58 file_output_stream& operator=(const file_output_stream&) = delete;
59 file_output_stream& operator=(file_output_stream&&) = delete;
60
64 ~file_output_stream() { (void)std::fclose(file_); }
65
72 void write(const unsigned char* data, std::size_t size) override {
73 if (std::fwrite(data, 1U, size, file_) != size) {
74 throw std::runtime_error("Failed to write data to a file.");
75 }
76 }
77
78private:
80 std::FILE* file_;
81};
82
83} // namespace msgpack_light
Class of streams to write data to files.
std::FILE * file_
File descriptor.
file_output_stream(const std::string &file_path)
Constructor.
file_output_stream(const char *file_path)
Constructor.
void write(const unsigned char *data, std::size_t size) override
Write data.
output_stream()=default
Constructor.
Namespace of this project.
Definition binary.h:33
STL namespace.
Definition of output_stream class.