johnyyonehand
johnyyonehand

Reputation: 52

Binary file writing/reading on different endians

A rather simple questions about safe ways to write constant in size structs (containing uint8_t, uint32_t etc) to binary file that would ensure it's readibility

  1. Is it accepted to use #pragma pack? (similiar to BITMAPFILEHEADER ) and then writing entire struct to file (so far it worked with bitmaps). Should I rather use a simple serialization to single bytes ( as shown here Serialization of struct)?

  2. What about endianness? How should one prepare for switch to different one? Is forcing eg little endian only and requiring application (in BE) to byteswap each element accepted?

My current project is rather simple one, but I would like to expand it in the future so I would rather try to avoid any pitfalls. I know that boost offers serialization, but for know I would like to handle stuff manually.

Upvotes: 0

Views: 135

Answers (1)

Joseph Artsimovich
Joseph Artsimovich

Reputation: 1519

Is it accepted to use #pragma pack?

That's something frowned upon. Packing a struct is going to violate data alignment requirements. On some architectures unaligned access is merely slower, on others it's outright forbidden. In the latter case the compiler is forced to generate code that will reassemble your data members from bytes every time you access them.

Instead of struct packing, you should be writing custom serialization code. That is, design your classes like you normally would, with encapsulation and stuff, and then just provide serialization / deserialization methods.

What about endianness? How should one prepare for switch to different one? Is forcing eg little endian only and requiring application (in BE) to byteswap each element accepted?

That's something perfectly accepted and in fact widely used. The alternative of having endiannes being encoded in data format itself is a bad idea IMHO, as it complicates your code for no good reason. When doing I/O, byte swapping is not going to be the performance bottleneck anyway.

Upvotes: 2

Related Questions