Alexander Hunziker wrote:
Hello group,
I have a program that reads data from a binary file. I know that at some
known position in the file there are 12 4 bytes long floating point
numbers. Here's how I read them now:
float temptriangle[12];
fread(&temptriangle, 4, 12, fp);
This works quite nicely, however it does so only if sizeof(float) is 4,
otherwise I'll get garbage.
Is there a cleaner way of doing it? Reading 4 bytes from a file into a
floating point variable?
"Cleanliness is next to Godliness and next to impossible,
too." You are aware, I hope, that different C implementations
use different binary representation for `float', so your binary
file may be meaningful only to the machine that wrote it. You
have already sacrificed a certain amount of cleanliness by
choosing to use a binary format.
That said, the code as written can be scrubbed to a somewhat
brighter gleam. First, get rid of the address-of `&' operator;
see Question 6.12 in the comp.lang.c Frequently Asked Questions
(FAQ) list <http://www.eskimo.com/~scs/C-faq/top.html> if you
don't understand why this is the right thing to do. Second,
you can rewrite the "magic numbers" `4' and `12' in terms of
the `sizeof' operator. This would give something like
fread(temptriangle, sizeof temptriangle[0],
sizeof temptriangle / sizeof temptriangle[0], fp);
(The third argument is correct only if `temptriangle' is an
actual array rather than a pointer; see Question 6.21 in the FAQ.)
Even this isn't quite as clean as it should be, because it
lacks one important feature: it doesn't check whether fread()
succeeded or failed. You really need something more like
if (fread(temptriangle, ...)
!= sizeof temptriangle / sizeof temptriangle[0])
complain_and_die();
See the Sixth Commandment at
<http://www.lysator.liu.se/c/ten-commandments.html>.
--
Eric Sosman
es*****@acm-dot-org.invalid