read(fd, &y, sizeof(y)) portability

buck%nrl-css at sri-unix.UUCP buck%nrl-css at sri-unix.UUCP
Sat Mar 3 01:06:57 AEST 1984


From:  Joe Buck <buck at nrl-css>


There are two meanings for portability here; in the more realistic (but
weaker) sense, this is a portable construct. Any C compiler can recover
objects (array, structure, int, etc) of type y written with
write(fd,&y,sizeof(y)) by using read(fd,&y,sizeof(y)).  Of course sizeof(y)
is different on different machines; that's the reason sizeof is included in
the language, to take care of machine dependencies in an elegant way.

There's a second, tougher standard of portability. This is, what if machine
A does the write and machine B does the read? For this case, even ints of
the same size may be nonportable because the VAX and PDP-11 have one way of
ordering bytes and everyone else (almost) has another. You have to encode
everything as char values to have any hope at all of this type of
portability; even then there are problems in that some bytes aren't eight
bits.

In summary, the use of sizeof with read and write is the proper thing to do
and should be encouraged.

ARPA: buck at nrl-css
UUCP: ...!decvax!nrl-css!buck

-Joe



More information about the Comp.unix.wizards mailing list