Gernot Frisch schreef:
template <class flt> void write(FILE* pF, const flt& f)
{
// this will definitely _not_ write
// an x-platfrom binary file
fwrite(&f, sizeof(f), 1, pF);
}
int main()
{
FILE* pF = fopen("test", "wb");
write(pF, 1.234);
}
How to make this work on any processor architecture, so the file
created is portable?
x-platform binary is by definition impossible. How many bits are there
in a byte? There's a reason CHAR_BIT exists. Now, as long as you stick
to the usual characters in the textual representation of a float (ie,
no locale-specific non-ASCII chars) these textual representations are
guanranteed to have an equivalent on every C++ implementation. I.e.
there is a char '0' everywhere, even though the binary representation
may have different values (or even lengths). That's how text is
portable - there is a hidden conversion that is logically defined.
Now, you can easily define a similar binary conversion by defining
a binary file as a sequence of numbers in the range [0,255]. Every
C++ implementation can generate such a file, and read it. Of course,
when moving a file from one system to another a conversion might be
required.
This still doesn't buy you what you want. The set of representable
values differs between different float implementations. In particular,
an implementation with 64-bits floats can create a binary file which
cannot be parsed on a system with 32-bits floats.
HTH,
Michiel Salters