Files

76 lines
2.1 KiB
C++
Raw Permalink 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
//----------------------------------------------------------------------------//
#include <boost/endian/detail/disable_warnings.hpp>
2008-05-30 15:26:33 +00:00
#include <iostream>
#include <cstdio>
#include <boost/endian/buffers.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
{
2014-12-05 09:05:05 -05:00
// 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
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_buf_at file_code;
big_int32_buf_at file_length;
little_int32_buf_at version;
little_int32_buf_at 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
{
header h;
BOOST_STATIC_ASSERT(sizeof(h) == 16U); // reality check
2008-05-30 15:26:33 +00:00
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
}