I'm currently working on a binary file format for some arbitrary values, including some strings, and string-length values, which are stored as uint32_t's.
But I was wondering, if I write the string length with fwrite to a file on a little-endian system, and read that value from the same file with fread on a big-endian system, will the oder of the bytes be reversed? And if so, what is the best practice to fix that?
EDIT: Surely there has to be some GNU functionality around that does this for me, and that is used, tested and validated for, like, 20 years?
Yes, fwrite and fread on an integer makes your file format unportable to another endianness, as other answers correctly state.
As of best practice, I would discourage any conditional byte flipping and endianness testing at all. Decide on the endianness of your file format, than write and read bytes, and make integers from them by ORing and shifting.
In other words, I agree with Rob Pike on the issue.
If I write the string length with fwrite to a file on a little-endian system, and read that value from the same file with fread on a big-endian system, will the oder of the bytes be reversed?
Yes. fwrite simply writes the memory contents to file in linear order. fread simply reads from file to memory in linear order.
What is the best practice to fix that?
Decide on an ordering for your files. Then write wrapper functions to write and read integers to/from files. Inside this function, conditionally flip the byte order if you're on a system with the opposite ordering.
(There are lots of questions here regarding determining the endianness of a system.)
Surely there has to be some GNU functionality around that does this for me
There's nothing in the standard library. However, POSIX defines a bunch of functions for this: ntohl, htonl, etc.. They're typically used for network transfer, but could equally be used for files.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With