conversion_use_case.cpp 1.5 KB

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