Proposal for Enhanced Binary Stream I/O

Introduction

The C++ standard library's stream I/O facilities are type-safe and very convenient for performing formatted (i.e. human readable) I/O, but offer only rudimentary and not very type-safe operations for performing binary I/O.  Although formatted I/O is often preferable, some applications need the speed and storage efficiency of binary I/O or need to interoperate with third-party applications that require binary file or network data formats.

Standard library streams can be opened with filemode std::ios_base::binary, so binary I/O is possible. But the only unformatted I/O functions available are get(), put(), read(), and write(). These operate only on char or array of char (with length explicitly specified), so require the user to write casts, are hard to use, and are error prone.

There have been many requests on Boost and various C++ newsgroups for unformatted binary I/O. For example, in 2003 Neal Becker wrote:

I wonder if anyone has code for implementing unformatted I/O?  What I have in mind is for the simple case where the application that reads data knows the data types, so this is not as complicated as the general marshalling situation.

This proposal provides a simple solution that works will standard library input and output streams. The one caveat is that they should be open with filemode std::ios_base::binary.

Synopsis

namespace boost
{
  template <class T>
  unspecified-type-1<T> bin(const T& x);

  template <class T>
  unspecified-type-2<T> bin(T& x);

  template <class T>
  std::ostream& operator<<(std::ostream& os, unspecified-type-1<T> x);

  template <class T>
  std::ostream& operator<<(std::ostream& os, unspecified-type-2<T> x);

  template <class T>
  std::istream& operator>>(std::istream& is, unspecified-type-2<T> x);
}

unspecified-type-1 and unspecified-type-2 are implementation supplied types.

Example

int main()
{
  int i = 0x41424344;
  std::cout << std::hex << i << " " << bin(i) << '\n';
  return 0;
}

On a little-endian machine, the output is:

41424344 DCBA

 


Last revised: 22 April, 2011

© Copyright Beman Dawes, 2009, 2011

Distributed under the Boost Software License, Version 1.0. See www.boost.org/ LICENSE_1_0.txt