Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!mips!spool.mu.edu!munnari.oz.au!goanna!ok From: ok@goanna.cs.rmit.oz.au (Richard A. O'Keefe) Newsgroups: comp.lang.c Subject: Re: Little problem with sizeof on PC Message-ID: <5381@goanna.cs.rmit.oz.au> Date: 24 Apr 91 06:35:13 GMT References: <1991Apr23.022057.29511@ux1.cso.uiuc.edu> <1991Apr23.050747.19705@agate.berkeley.edu> Organization: Comp Sci, RMIT, Melbourne, Australia Lines: 36 In article <1991Apr23.050747.19705@agate.berkeley.edu>, c60b-1eq@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.