endian_example.cpp 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // endian_example.cpp -------------------------------------------------------//
  2. // Copyright Beman Dawes, 2006
  3. // Distributed under the Boost Software License, Version 1.0.
  4. // See http://www.boost.org/LICENSE_1_0.txt
  5. // See library home page at http://www.boost.org/libs/endian
  6. //----------------------------------------------------------------------------//
  7. #include <boost/endian/detail/disable_warnings.hpp>
  8. #include <iostream>
  9. #include <cstdio>
  10. #include <boost/endian/buffers.hpp>
  11. #include <boost/static_assert.hpp>
  12. using namespace boost::endian;
  13. namespace
  14. {
  15. // This is an extract from a very widely used GIS file format. Why the designer
  16. // decided to mix big and little endians in the same file is not known. But
  17. // this is a real-world format and users wishing to write low level code
  18. // manipulating these files have to deal with the mixed endianness.
  19. struct header
  20. {
  21. big_int32_buf_at file_code;
  22. big_int32_buf_at file_length;
  23. little_int32_buf_at version;
  24. little_int32_buf_at shape_type;
  25. };
  26. const char* filename = "test.dat";
  27. }
  28. int main(int, char* [])
  29. {
  30. header h;
  31. BOOST_STATIC_ASSERT(sizeof(h) == 16U); // reality check
  32. h.file_code = 0x01020304;
  33. h.file_length = sizeof(header);
  34. h.version = 1;
  35. h.shape_type = 0x01020304;
  36. // Low-level I/O such as POSIX read/write or <cstdio> fread/fwrite is sometimes
  37. // used for binary file operations when ultimate efficiency is important.
  38. // Such I/O is often performed in some C++ wrapper class, but to drive home the
  39. // point that endian integers are often used in fairly low-level code that
  40. // does bulk I/O operations, <cstdio> fopen/fwrite is used for I/O in this example.
  41. std::FILE* fi = std::fopen(filename, "wb"); // MUST BE BINARY
  42. if (!fi)
  43. {
  44. std::cout << "could not open " << filename << '\n';
  45. return 1;
  46. }
  47. if (std::fwrite(&h, sizeof(header), 1, fi)!= 1)
  48. {
  49. std::cout << "write failure for " << filename << '\n';
  50. return 1;
  51. }
  52. std::fclose(fi);
  53. std::cout << "created file " << filename << '\n';
  54. return 0;
  55. }