No, binary (de)serialization is not directly supported systematically by the library. The read()
function will move the stream pointer along, but I don't think you can get around a platform-dependent piece of code for interpreting the byte stream:
std::infile thefile("data.bin", "rb");
float f;
double d;
uint32_t i;
// the following is OK and doesn't constitute type punning
char * const pf = reinterpret_cast<char*>(&f);
char * const pd = reinterpret_cast<char*>(&d);
char * const pi = reinterpret_cast<char*>(&i);
// the following may or may not give you what you expect
// Caveat emptor, and add your own platform-specific code here.
thefile.read(pf, sizeof(float));
thefile.read(pd, sizeof(double));
thefile.read(pi, sizeof(uint32_t));
In the case of reading unsigned integral values only, you can perform an algebraic extraction which is in some sense type safe and only requires you to know the endianness of the serialized data format:
unsigned char buf[sizeof(uint32_t)];
thefile.read(reinterpret_cast<char*>(buf), sizeof(uint32_t));
uint32_t n = buf[0] + (buf[1] << 8) + (buf[2] << 16) + (buf[3] << 24); // little-endian
Reading floating point data in binary is particularly irksome because you have to know quite a lot of extra information about your data stream: Does it use IEEE754? (Does your platform?) What's the enidanness (float endianness is independent from integer endianness)? Or is it represented as something else entirely? Good documentation of the file format is crucial.
In C, you would use fread()
and C-style casts, char * const pf = (char*)(&f)
.