// C++ Standard Library
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <fstream>
#include <iostream>
#include <numeric>
// POSIX Library (for mmap)
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <unistd.h>
constexpr char MAGIC[8] = { "1234567" };
struct Header
{
char magic[sizeof (MAGIC)] = { '\0' };
std::uint64_t size =
{
0};
};
static_assert (sizeof (Header) == 16, "Header size should be 16 bytes");
static_assert (alignof (Header) == 8, "Header alignment should be 8 bytes");
void
write_binary_data (const char *filename)
{
Header header;
std::copy_n (MAGIC, sizeof (MAGIC), header.magic);
header.size = 100u;
std::ofstream fp (filename, std::ios::out | std::ios::binary);
fp.write (reinterpret_cast < const char *>(&header), sizeof (Header));
for (auto k = 0u; k < header.size; ++k)
{
double value = static_cast < double >(k);
fp.write (reinterpret_cast < const char *>(&value), sizeof (double));
}
}
double
read_binary_data (const char *filename)
{
// POSIX mmap API
auto fp =::open (filename, O_RDONLY);
struct stat sb;
::fstat (fp, &sb);
auto data =
static_cast <
char *>(::mmap (nullptr, sb.st_size, PROT_READ, MAP_PRIVATE, fp, 0));
::close (fp);
// end of POSIX mmap API (all error handling ommitted)
// UB1
const auto header = reinterpret_cast < const Header * >(data);
// UB2
if (!std::equal (MAGIC, MAGIC + sizeof (MAGIC), header->magic))
{
throw std::runtime_error ("Magic word mismatch");
}
// UB3
auto beg = reinterpret_cast < const double *>(data + sizeof (Header));
// UB4
auto end = std::next (beg, header->size);
// UB5
auto sum = std::accumulate (beg, end, double { 0 });
::munmap (data, sb.st_size);
return sum;
}
int
main ()
{
const double expected = 4950.0;
write_binary_data ("test-data.bin");
if (auto sum = read_binary_data ("test-data.bin"); sum == expected)
{
std::cout << "as expected, sum is: " << sum << "\n";
}
else
{
std::cout << "error\n";
}
}
1234567 d �? @ @ @ @ @ @ @ "@ $@ &@ (@ *@ ,@ .@ 0@ 1@ 2@ 3@ 4@ 5@ 6@ 7@ 8@ 9@ :@ ;@ <@ =@ >@ ?@ @@ �@@ A@ �A@ B@ �B@ C@ �C@ D@ �D@ E@ �E@ F@ �F@ G@ �G@ H@ �H@ I@ �I@ J@ �J@ K@ �K@ L@ �L@ M@ �M@ N@ �N@ O@ �O@ P@ @P@ �P@ �P@ Q@ @Q@ �Q@ �Q@ R@ @R@ �R@ �R@ S@ @S@ �S@ �S@ T@ @T@ �T@ �T@ U@ @U@ �U@ �U@ V@ @V@ �V@ �V@ W@ @W@ �W@ �W@ X@ @X@ �X@ �X@