diff options
author | Lorry Tar Creator <lorry-tar-importer@baserock.org> | 2015-04-08 03:09:47 +0000 |
---|---|---|
committer | <> | 2015-05-05 14:37:32 +0000 |
commit | f2541bb90af059680aa7036f315f052175999355 (patch) | |
tree | a5b214744b256f07e1dc2bd7273035a7808c659f /libs/endian/example/endian_example.cpp | |
parent | ed232fdd34968697a68783b3195b1da4226915b5 (diff) | |
download | boost-tarball-master.tar.gz |
Imported from /home/lorry/working-area/delta_boost-tarball/boost_1_58_0.tar.bz2.HEADboost_1_58_0master
Diffstat (limited to 'libs/endian/example/endian_example.cpp')
-rw-r--r-- | libs/endian/example/endian_example.cpp | 75 |
1 files changed, 75 insertions, 0 deletions
diff --git a/libs/endian/example/endian_example.cpp b/libs/endian/example/endian_example.cpp new file mode 100644 index 000000000..b9e17ecf5 --- /dev/null +++ b/libs/endian/example/endian_example.cpp @@ -0,0 +1,75 @@ +// endian_example.cpp -------------------------------------------------------// + +// Copyright Beman Dawes, 2006 + +// Distributed under the Boost Software License, Version 1.0. +// See http://www.boost.org/LICENSE_1_0.txt + +// See library home page at http://www.boost.org/libs/endian + +//----------------------------------------------------------------------------// + +#include <boost/endian/detail/disable_warnings.hpp> + +#include <iostream> +#include <cstdio> +#include <boost/endian/buffers.hpp> +#include <boost/static_assert.hpp> + +using namespace boost::endian; + +namespace +{ + // This is an extract from a very widely used GIS file format. Why the designer + // decided to mix big and little endians in the same file is not known. But + // this is a real-world format and users wishing to write low level code + // manipulating these files have to deal with the mixed endianness. + + struct header + { + big_int32_buf_at file_code; + big_int32_buf_at file_length; + little_int32_buf_at version; + little_int32_buf_at shape_type; + }; + + const char* filename = "test.dat"; +} + +int main(int, char* []) +{ + header h; + + BOOST_STATIC_ASSERT(sizeof(h) == 16U); // reality check + + h.file_code = 0x01020304; + h.file_length = sizeof(header); + h.version = 1; + h.shape_type = 0x01020304; + + // Low-level I/O such as POSIX read/write or <cstdio> fread/fwrite is sometimes + // used for binary file operations when ultimate efficiency is important. + // Such I/O is often performed in some C++ wrapper class, but to drive home the + // point that endian integers are often used in fairly low-level code that + // does bulk I/O operations, <cstdio> fopen/fwrite is used for I/O in this example. + + std::FILE* fi = std::fopen(filename, "wb"); // MUST BE BINARY + + if (!fi) + { + std::cout << "could not open " << filename << '\n'; + return 1; + } + + if (std::fwrite(&h, sizeof(header), 1, fi)!= 1) + { + std::cout << "write failure for " << filename << '\n'; + return 1; + } + + std::fclose(fi); + + std::cout << "created file " << filename << '\n'; + + return 0; +} |