Mail Archives: djgpp/1998/04/04/01:25:50
At 12:18 4/3/1998 GMT, Fist1000 wrote:
>Not sure where I should post this, but here goes:
>
>A friend of mine has written a program in TP7 and in it he uses a bunch of
>reals and writes them to disk. I'm helping him port his code to C (Watcom C),
>but I'm at a loss as to how I read in this data from a C program. For example,
>I wrote this test in Pascal:
>
>(**********************)
>program WriteReal;
>var
> r : real;
> f : file of real;
>begin
> r := 3.14159;
> assign(f,'real.log');
> rewrite(f);
> write(f, r);
> close(f);
>end.
>(**********************)
>
>Then I wrote a simple C prog to read the file written:
>
>//////////////////////////////
>void main(void)
> {
> double dbl = 0.0;
>
> FILE * f = fopen("real.log", "rb");
> fread(&dbl, 6, 1, f);
> fclose(f);
>
> printf("%f", dbl);
> }
>//////////////////////////////
>
>Yet when I run the C prog, I get an output of 0.000000. Does anyone know how to
>do this?
There are several layers of problems here. First, as you have guessed, TP
uses a 6-byte `Real' type, which is unlike anything supported by actual
floating point hardware. If you must write binary floating-point numbers to
a file, you can compile your TP program with the $N+ option and use the
`Single' or `Double' types instead of `Real'. (`Extended' lacks the padding
which GCC expects and will confuse the issue still more; I'd suggest not to
use it.) `Single' should correspond to C's `float', and `Double' to `double'.
However, an even better solution is to write to the file in some more
reasonable format, like ASCII. Many of your problems will go away if you use:
writeln(f);
...
scanf("%f", &f);
And no, it's really not all that much more inefficient. It has the added
advantage that it will continue to work should you decide to port to another
platform someday.
An additional pedantic note: `main' must return an `int'.
Nate Eldredge
eldredge AT ap DOT net
- Raw text -