summaryrefslogtreecommitdiff
path: root/libs/endian/example/conversion_use_case.cpp
blob: 76329bb7b74e130ac9bacfa156b22d4c76c42b75 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//  endian/example/conversion_use_case.cpp 

//  Copyright Beman Dawes 2014

//  Distributed under the Boost Software License, Version 1.0.
//  See http://www.boost.org/LICENSE_1_0.txt

//  This program reads a binary file of fixed length records, with a format defined
//  in a header file supplied by a third-party. The records inserted into a vector,
//  and the vector is sorted. The sorted records are then written to an output file.

//  Full I/O error testing omitted for brevity, So don't try this at home.

#include "third_party_format.hpp"
#include <boost/endian/conversion.hpp>
#include <vector>
#include <fstream>
#include <algorithm>
#include <iostream>

using third_party::record;

int main()
{
  std::ifstream in("data.bin", std::ios::binary);
  if (!in) { std::cout << "Could not open data.bin\n"; return 1; }

  std::ofstream out("sorted-data.bin", std::ios::binary);
  if (!out) { std::cout << "Could not open sorted-data.bin\n"; return 1; }

  record rec;
  std::vector<record> recs;

  while (!in.eof())  // read each record
  {
    in.read((char*)&rec, sizeof(rec));
    rec.balance = boost::endian::big_to_native(rec.balance);  // reverse if needed
    recs.push_back(rec);
  }

  std::sort(recs.begin(), recs.end(),  // decending sort by balance
    [](const record& lhs, const record& rhs) -> bool
      { return lhs.balance > rhs.balance; });

  for (auto &out_rec : recs)  // write each record
  {
    out_rec.balance = boost::endian::native_to_big(rec.balance);  // reverse if needed
    out.write((const char*)&out_rec, sizeof(out_rec));
  }
    
}