fread() portability problem

Richard A. O'Keefe ok at goanna.cs.rmit.oz.au
Tue Jun 25 18:57:39 AEST 1991


In article <shores.677815060 at fergvax>, shores at fergvax.unl.edu (Shores) writes:
> I'm hoping this problem is only with ultrix.  Let's say I have fopen()ed
> a file and the first 2 bytes are 0x0006.  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! 

And so it ruddy well *should*.  That's what you *told* it to do!

You have run into the well known problem that
	+-------------------------------+
	| BINARY FILES ARE NOT PORTABLE |
	+-------------------------------+
A Mac and a NeXT both use members of the MC680x0 family.  You were thus
using essentially the same machine in your first two attempts.

Using 2L and 1L is not portable either, nor is the assumption that there
is such an animal as a "2-byte integer".  (ANSI guarantees that 'short'
is _at least_ 2 bytes, but it might be more.)  What you want to do is

	int nbor_short(short *p, FILE *f)	/* Network Byte Order Read */
	    {					/* Short int		   */
		int c1, c2;
		c1 = getc(f); if (c1 == EOF) return c1;
		c2 = getc(f); if (c2 == EOF) return c2;
		*p = (c1 << 8) + c2;
		return 0;			/* returns 0 for success */
	    }					/* EOF for failure */

or something similar.  I suggest that you do
	% man byteorder
	% man ntohs
on your Ultrix system.  The latter will tell you how
	... fread(&twoBytes, 2, 1, inFile) ...
	twoBytes = ntohs(twoBytes);
is a more portable way to pick up a pair of bytes as a short.  Your NeXT
machine should have these manual entries (and the functions they are about)
too.

This is not the only problem you will have.  The Mac and the NeXT use the
same floating-point format.  VAXes don't.  (VAX floating-point was about
as good as you could get before IEEE.)

-- 
I agree with Jim Giles about many of the deficiencies of present UNIX.



More information about the Comp.lang.c mailing list