Files
boost_endian/libs/endian/example/endian_example.cpp
T

79 lines
2.2 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
#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/detail/lightweight_test.hpp>
2011-05-22 20:33:28 +00:00
#include <boost/detail/lightweight_main.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. I have no idea
// 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
{
big32_t file_code;
big32_t file_length;
little32_t version;
little32_t shape_type;
};
const char * filename = "test.dat";
}
2011-05-22 20:33:28 +00:00
int cpp_main(int, char * [])
2008-05-30 15:26:33 +00:00
{
BOOST_TEST_EQ( sizeof( header ), 16U ); // requirement for interoperability
2008-05-30 15:26:33 +00:00
header h;
h.file_code = 0x04030201;
h.file_length = sizeof( header );
h.version = -1;
h.shape_type = 0x04030201;
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 )
{
std::cout << "write failure for " << filename << '\n';
return 1;
}
std::fclose( fi );
std::cout << "created file " << filename << '\n';
return ::boost::report_errors();
2008-05-30 15:26:33 +00:00
}