Zserio C++17 runtime library 1.3.0
Built for Zserio 2.20.0
Loading...
Searching...
No Matches
FileUtil.cpp
Go to the documentation of this file.
1#include <fstream>
2#include <string_view>
3
5#include "zserio/FileUtil.h"
6
7namespace zserio
8{
9
10void writeBufferToFile(const uint8_t* buffer, size_t bitSize, BitsTag, std::string_view fileName)
11{
12 std::ofstream stream(fileName.data(), std::ofstream::binary | std::ofstream::trunc);
13 if (!stream)
14 {
15 throw CppRuntimeException("writeBufferToFile: Failed to open '") << fileName << "' for writing!";
16 }
17
18 const size_t byteSize = (bitSize + 7) / 8;
19 if (!stream.write(reinterpret_cast<const char*>(buffer), static_cast<std::streamsize>(byteSize)))
20 {
21 throw CppRuntimeException("writeBufferToFile: Failed to write '") << fileName << "'!";
22 }
23}
24
26{
27 std::ifstream stream(fileName.data(), std::ifstream::binary);
28 if (!stream)
29 {
30 throw CppRuntimeException("readBufferFromFile: Cannot open '") << fileName << "' for reading!";
31 }
32
33 (void)stream.seekg(0, stream.end);
34 const std::streampos fileSize = stream.tellg();
35 (void)stream.seekg(0);
36
37 if (static_cast<int>(fileSize) == -1)
38 {
39 throw CppRuntimeException("readBufferFromFile: Failed to get file size of '") << fileName << "'!";
40 }
41
42 const size_t sizeLimit = std::numeric_limits<size_t>::max() / 8;
43 if (static_cast<uint64_t>(fileSize) > sizeLimit)
44 {
45 throw CppRuntimeException("readBufferFromFile: File size exceeds limit '") << sizeLimit << "'!";
46 }
47
48 BitBuffer bitBuffer(static_cast<size_t>(fileSize) * 8);
49 if (!stream.read(reinterpret_cast<char*>(bitBuffer.getBuffer()),
50 static_cast<std::streamsize>(bitBuffer.getByteSize())))
51 {
52 throw CppRuntimeException("readBufferFromFile: Failed to read '") << fileName << "'!";
53 }
54
55 return bitBuffer;
56}
57
58} // namespace zserio
void writeBufferToFile(const uint8_t *buffer, size_t bitSize, BitsTag, std::string_view fileName)
Definition FileUtil.cpp:10
BitBuffer readBufferFromFile(std::string_view fileName)
Definition FileUtil.cpp:25