This is true not only when writing to files, but also in memory. It is a fact that the structure is filled in memory, which leads to the appearance of an addition in the file if the structure is written by byte.
In general, it is very difficult to accurately reproduce the exact filling pattern, although, I think, some heuristics will take you quite far. This helps if you have a structure declaration for analysis.
Typically, fields greater than one char will be aligned so that their initial offset within the structure is a multiple of their size. This means that short will usually be at uniform offsets (divided by 2, assuming sizeof (short) == 2 ), and double will be at offsets divisible by 8, etc.
UPDATE . This is due to such reasons (as well as for reasons related to content) that it is usually a bad idea to dump entire structures into files. It is better to do this across the field, for example:
put_char(out, ac); put_int(out, ai);
Assuming that the put functions only write the bytes needed for the value, this will release the struct version to the file without problems to solve the problem. It is also possible to provide correct, well-known byte ordering by writing these functions accordingly.
source share