Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!sdd.hp.com!caen!uwm.edu!bionet!agate!e260-1d.berkeley.edu!c60b-1eq From: c60b-1eq@e260-1d.berkeley.edu (Noam Mendelson) Newsgroups: comp.lang.c Subject: Re: Little problem with sizeof on PC Message-ID: <1991Apr23.050747.19705@agate.berkeley.edu> Date: 23 Apr 91 05:07:47 GMT References: <1991Apr23.022057.29511@ux1.cso.uiuc.edu> Sender: root@agate.berkeley.edu (Charlie Root) Organization: University of California, Berkeley Lines: 40 In article <1991Apr23.022057.29511@ux1.cso.uiuc.edu> allender@ux1.cso.uiuc.edu (Mark Allender) writes: >I'm having a litle problem that I have a suspicision about, but want >to clarify. Here's the situation.... >struct header { > ......... >}; >Now, I want to read the beginning of a binary file into this structure, >so I do something like this: > struct header Header; > if ((readnum = read(fd, (char *)(&Header), sizeof(Header))..... Hmmm. That should be: if ((readnum = read(fd, (struct header *)(&Header), sizeof(Header)) ... >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). Either that or your miscounted (I didn't verify your figure :-) In any case, I suggest you check your compiler for a possible byte alignment option (I know Turbo C 2.0 has this), and recompile. >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)).... > >Seems like kind of a bad way to fix things.... That would probably work on a PC, assuming the structure was word-aligned. But it's also dependent on your compiler. The best thing would be to restructure the data file, using 202 byte blocks instead of 201 to be on the safe side. At worst, you're increasing the size of the data file by about .5%. -- +==========================================================================+ | Noam Mendelson ..!ucbvax!web!c60b-1eq | "I haven't lost my mind, | | c60b-1eq@web.Berkeley.EDU | it's backed up on tape | | University of California at Berkeley | somewhere." |