• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //  endian/example/conversion_use_case.cpp
2 
3 //  Copyright Beman Dawes 2014
4 
5 //  Distributed under the Boost Software License, Version 1.0.
6 //  See http://www.boost.org/LICENSE_1_0.txt
7 
8 //  This program reads a binary file of fixed length records, with a format defined
9 //  in a header file supplied by a third-party. The records inserted into a vector,
10 //  and the vector is sorted. The sorted records are then written to an output file.
11 
12 //  Full I/O error testing omitted for brevity, So don't try this at home.
13 
14 #include "third_party_format.hpp"
15 #include <boost/endian/conversion.hpp>
16 #include <vector>
17 #include <fstream>
18 #include <algorithm>
19 #include <iostream>
20 
21 using third_party::record;
22 
main()23 int main()
24 {
25   std::ifstream in("data.bin", std::ios::binary);
26   if (!in) { std::cout << "Could not open data.bin\n"; return 1; }
27 
28   std::ofstream out("sorted-data.bin", std::ios::binary);
29   if (!out) { std::cout << "Could not open sorted-data.bin\n"; return 1; }
30 
31   record rec;
32   std::vector<record> recs;
33 
34   while (!in.eof())  // read each record
35   {
36     in.read((char*)&rec, sizeof(rec));
37     rec.balance = boost::endian::big_to_native(rec.balance);  // reverse if needed
38     recs.push_back(rec);
39   }
40 
41   std::sort(recs.begin(), recs.end(),  // decending sort by balance
42     [](const record& lhs, const record& rhs) -> bool
43       { return lhs.balance > rhs.balance; });
44 
45   for (auto &out_rec : recs)  // write each record
46   {
47     out_rec.balance = boost::endian::native_to_big(out_rec.balance);  // reverse if needed
48     out.write((const char*)&out_rec, sizeof(out_rec));
49   }
50 
51 }
52