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