Little problem with sizeof on PC

D'Arcy J.M. Cain darcy at druid.uucp
Wed Apr 24 22:29:13 AEST 1991


In article <1991Apr23.022057.29511 at ux1.cso.uiuc.edu> Mark Allender writes:
>struct header {
>	int version[2];
>	char unused[40];
>	int stuff[8];
>	char bogus;
>	char mode;
>	int time;
>	char unused2[90];
>	char filler[38];
>	char filler2[15]
>	float number;
>};
>
>The total size of the structure is 201 bytes (count it if you wish....).
>Now, I want to read the beginning of a binary file into this structure,

I have already seen some responses (One completely bogus - nettor beware)
but I get the impression that what you have here is the header from an
existing file format that you have no control over.  If this is the case
then you will have to read this piece by piece.  The main culprit is the
filler2 element.  This will probably cause a misalignment on most systems.
If you expect portability you will also have problems with the declarations
of version and time as they can be different sizes on different systems.
If you use short and long in these situations your code will go further
before it blows up but you still have no guarantees.

Depending on the project I have two ways of dealing with this problem.
One way is to write a separate module with routines to read and write
the various types of items from the file or simply to read the entire
header into the structure.  The advantage to this method is speed in
that you can write separate modules for different systems tuning it to
the natural byte order etc.  Since in most case speed isn't all that
important (you suggest you only do this operation once) the best way
might be to write the code in a system independent way.  This simplifies
moving to other platforms.  An example:
    version[0] = getc(fp) << 16;
    version[0] += getc(fp);

Slow and bulky but will work on any platform.  Note the assumption about
the byte order in the file but none about the byte order on the machine.

>In any case, what is the best way around this problem.  Could I do something
>like
>	if ((readnum = read(fd, (char *)(&Header), sizeof(Header) - 1))....

I doubt this will work since the padding is probably not at the end of
the structure.  You will probably get the first byte of number in
filler2 and a completely bogus value in number.  On some systems it
would get worse.

-- 
D'Arcy J.M. Cain (darcy at druid)     |
D'Arcy Cain Consulting             |   There's no government
Toronto, Ontario, Canada           |   like no government!
+1 416 424 2871                    |



More information about the Comp.lang.c mailing list