Little problem with sizeof on PC

Richard A. O'Keefe ok at goanna.cs.rmit.oz.au
Wed Apr 24 16:35:13 AEST 1991


In article <1991Apr23.050747.19705 at agate.berkeley.edu>, c60b-1eq at e260-1d.berkeley.edu (Noam Mendelson) writes:
> >Now, I want to read the beginning of a binary file into this structure,

> >Things don't seem to get done correctly at this point.  A little investigation
> >shows that sizeof(Header) return 202, and not 201.  This is clearly not
> >what I want to do.

> Your compiler probably word-aligned the structure (202 is on a word boundary).

It's not just that.  The compiler may well have placed *elements* of the
structure at "natural alignment boundaries" as well.  Assuming 1 byte
chars (8-bit aligned), 2 byte integers (16-bit aligned), and 4-byte
floats (16-bit aligned), I would not be surprised to find a "filler" byte
inserted *before* the last member.

> >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))....

> That would probably work on a PC, assuming the structure was word-aligned.

It the compiler has inserted padding *within* the structure (e.g. in order
to align the float member on a 16-bit boundary) then it certainly _won't_
work.

If you want to save C structures to a file and read them back,
you should be using fwrite() and fread() on a FILE* opened in binary mode.
If you want to read records written by some other language, you CAN'T
rely on C structs.  You just do not have enough control over the storage
layout of a struct to do it.  You will have to write a function that
reads values from the stream a chunk at a time and stores them into the
struct.

-- 
Bad things happen periodically, and they're going to happen to somebody.
Why not you?					-- John Allen Paulos.



More information about the Comp.lang.c mailing list