Reputation: 139
If I store a float in a file via this code
fwrite((void*)(&v), sizeof(v), 1, f); // v is a float.
how often will a program reading the file with this code cause a runtime error because float is 8 bytes instead of 4?
float v;
fread((void*)(&v), sizeof(v), 1, f);
return v;
Can I always read 4 bytes and cast that to an 8 byte float? Would that be more portable?
Emphasis on different Windows Platforms 64 bit vs 32 bit.
Upvotes: 2
Views: 1203
Reputation: 212969
It's always better to store data as text rather than raw binary if you reasonably can. This avoids the above problem and a myriad other issues such as:
It also makes the data usable by other programs if needed.
The down-side of course is that text requires more storage, so if you have a lot of data then text may not be an option.
Upvotes: 2
Reputation: 18411
On Windows platform, sizeof(float)
is always 4 bytes irrespective if it is 32-bit or 64-bit process/OS. Don't know about standard, but on most platforms, sizeof a float is four bytes.
Upvotes: 0
Reputation: 9786
float pretty universal in referring to an IEEE single precision float, regardless if the platform is 32bit or 64bit.
Upvotes: 0
Reputation: 4241
The size of float
might change, but double
does not. Are you sure it wouldn't be a better idea to use a double
then for that purpose? A double
is always 8 bytes.
Upvotes: 1
Reputation: 96241
I would be less worried about the size of the float and more worried about the endianness of it. I'd say the vast majority of C++ implementation use IEEE 754 which would mean float is always going to be 32 bits and double 64 bits.
You may wish to just serialize a text representation of the value, or else take particular care to make sure that the byte order is correct.
Upvotes: 6