i/o of floats

Tom Christiansen tchrist at convex.COM
Wed Aug 22 20:56:26 AEST 1990


In article <9232 at jpl-devvax.JPL.NASA.GOV> charest at AI-Cyclops.JPL.NASA.GOV writes:
>I have a large (~40 MB) file of floating point values stored in binary
>Now how do I interpret each 4-byte "word" of record as a floating point number?
>I merely need to print each float onto stdout. 

If I understand your problem, it's pretty easy to solve.

They're floats on the disk, so read them in that way.  I assume that your
machine is also in IEEE format.  Otherwise you'll have to write an IEEE-
to-native conversion function, probably using bit fields or bit masks.

The simple case (same FP format) is easy.  I use stdio because you
did and it optimizes the I/O buffering pretty well.  

    /*
     * read n floats in binary from stdio pointer fp,
     * printing on stdout one per line.  returns i/o success.
     * CAVEAT EMPTOR: untested
     */
    #define FOK(F) (!(feof(F) || ferror(F)))

    read_floats(fp, n)
	FILE *fp;
	int   n;
    {
	float num;

	ASSERT(fp != NULL);
	ASSERT(n > 0);

	while (FOK(fp) && n-- && fread(&num, sizeof(num), 1, fp)) 
	    printf("%14.8f\n", num);

	return FOK(fp);
    }

--tom
--
 "UNIX was never designed to keep people from doing stupid things, because 
  that policy would also keep them from doing clever things." [Doug Gwyn]



More information about the Comp.lang.c mailing list