fread() portability problem

der Mouse mouse at thunder.mcrcim.mcgill.edu
Sat Jun 29 00:58:44 AEST 1991


In article <shores.677815060 at fergvax>, shores at fergvax.unl.edu (Shores) writes:

> I'm hoping this problem is only with ultrix.

Actually it's a problem with your understanding of multi-byte integers.

> Let's say I have fopen()ed a file and the first 2 bytes are 0x0006.

This doesn't really make sense.  The first two bytes might be 0x00 and
0x06, or 0x06 and 0x00, but to say that they are 0x0006 is at best
misleading.

> Now on my mac (and a NeXT) I can say fread (&twoBytes, 2L, 1L,
> inFile) and it will put the number 6 into a 2 byte integer, like I
> want.  But when I port this code to a VAX running ultrix, the same
> statement puts 0x0600 into the integer!

I guess the first two bytes are 0x00 and 0x06.

This is the famous byte-order problem.  Your fread (or the
corresponding fwrite) is treating an integer as an array of bytes.  How
a multi-byte integer is stored in the various bytes is machine- (and
perhaps compiler-) dependent.  Your Mac and NeXT use so-called
big-endian processors, storing the most-significant 8 bits of the
integer value in the first byte, the next 8 bits next, and so on; the
VAX is what's called little-endian, going the other way around.

> I would like to post my finished code and have it run on a wide array
> of unix machines; are other machines going to give me this problem
> too,

Never never try to move binary files between machines; if you must
write binary files, make sure you read them back on the same machine.
If you really must, use something like XDR to serialize data in a
machine-independent way, or at *least* use ntohl() and friends to
convert integers to a standard byte order.  (Trying to do this with
floats is just asking for trouble.)

> I'm about to try to replace my fread calls with a bunch of ugly
> getc()s, like create a getword() which calls getc() twice, and return
> (char1 << 8) + char2.

That, or something like it, is probably the right approach.  Why do you
dislike it so much?

					der Mouse

			old: mcgill-vision!mouse
			new: mouse at larry.mcrcim.mcgill.edu



More information about the Comp.lang.c mailing list