Files
endian/example/endian_example.cpp
T

79 lines
2.1 KiB
C++
Raw Normal View History

2008-05-30 15:26:33 +00:00
// endian_example.cpp -------------------------------------------------------//
// Copyright Beman Dawes, 2006
2009-03-19 14:33:59 +00:00
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
2008-05-30 15:26:33 +00:00
// See library home page at http://www.boost.org/libs/endian
//----------------------------------------------------------------------------//
#define _CRT_SECURE_NO_DEPRECATE // quiet VC++ 8.0 foolishness
#define _SCL_SECURE_NO_WARNINGS
2008-05-30 15:26:33 +00:00
#include <boost/endian/detail/disable_warnings.hpp>
2008-05-30 15:26:33 +00:00
#include <iostream>
#include <cstdio>
#include <boost/endian/types.hpp>
#include <boost/static_assert.hpp>
2008-05-30 15:26:33 +00:00
2011-05-22 20:33:28 +00:00
using namespace boost::endian;
2008-05-30 15:26:33 +00:00
namespace
{
// This is an extract from a very widely used GIS file format. Who knows
2013-05-23 07:33:06 -04:00
// why a designer would mix big and little endians in the same file? But
2009-03-19 14:33:59 +00:00
// this is a real-world format and users wishing to write low level code
2008-05-30 15:26:33 +00:00
// manipulating these files have to deal with the mixed endianness.
struct header
{
big_int32_t file_code;
big_int32_t file_length;
little_int32_t version;
little_int32_t shape_type;
2008-05-30 15:26:33 +00:00
};
const char* filename = "test.dat";
2008-05-30 15:26:33 +00:00
}
int main(int, char* [])
2008-05-30 15:26:33 +00:00
{
BOOST_STATIC_ASSERT(sizeof(header) == 16U); // reality check
2008-05-30 15:26:33 +00:00
header h;
h.file_code = 0x01020304;
h.file_length = sizeof(header);
h.version = 1;
h.shape_type = 0x01020304;
2008-05-30 15:26:33 +00:00
2009-03-19 14:33:59 +00:00
// 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.
2008-05-30 15:26:33 +00:00
std::FILE* fi = std::fopen(filename, "wb"); // MUST BE BINARY
2008-05-30 15:26:33 +00:00
if (!fi)
2008-05-30 15:26:33 +00:00
{
std::cout << "could not open " << filename << '\n';
return 1;
}
if (std::fwrite(&h, sizeof(header), 1, fi)!= 1)
2008-05-30 15:26:33 +00:00
{
std::cout << "write failure for " << filename << '\n';
return 1;
}
std::fclose(fi);
2008-05-30 15:26:33 +00:00
std::cout << "created file " << filename << '\n';
return 0;
2008-05-30 15:26:33 +00:00
}