I want to read in some data from a file. Say an integer:
fread(&var1, 4, 1, f);
Where var1 would be an integer. But then I got to thinking that this is not safe as there isn’t any guarantee that an integer is 4 bytes long. (I’m ignoring other issues like feof and ferror for the sake of this question).
I also soon realised that there were even more issues than just int size, such as the endianness of the system, and probably others which I haven’t even thought of.
So, what is the best way to ensure that you data being read in is interpreted properly? So far, the only thing I can think of is to just store the data as text rather than as binary data, read in the text, and convert it at run time. I would guess that no matter the solution though, if you wanted to ensure that it is portable, it would always involve some form of conversion anyway.
Thank you.
To avoid the size problem, you should be doing:
If you’re worried that the size of
intmight vary between the platform that writes the data and the platform that reads the data, then you have a more fundamental problem. In this scenario, you should avoid usingint,short, etc., and use the types defined in<stdint.h>, such asint16_t,uint32_t.To deal with endianness issues, you should consider writing helper functions that explicitly write/read the individual bytes in a known order, such as:
All of the above applies only to integer types. For floating-point types, there is no perfect universal solution.