I need to write some C code that writes doubles out to file.
For some values, fwrite writes the correct 8-byte binary to file. For other values, it seems to prepend an extra 9th byte. For example, this code writes 9 bytes comprising x0d, followed by the correct 8 bytes:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <float.h>
#define PI 3.14159265358979323846
int main()
{
// Generate a number
double x = -3.0 * cos(PI * 5.0 / 8.0);
printf("%.*e\n", DECIMAL_DIG, x);
// Uncomment this to get an 8-byte file instead of 9
// x = (float) x;
// Write number to file
FILE* fw = fopen("out.bin", "w");
if (fw != NULL)
{
size_t Nw = fwrite(&x, sizeof(double), 1, fw);
printf("Wrote %i values to file.\n", Nw);
if (fclose(fw) != 0)
return (EXIT_FAILURE);
}
else
return (EXIT_FAILURE);
return (EXIT_SUCCESS);
}
However, if I change the value, for example to double x = -3.0 * cos(PI * 3.0 / 8.0);
, or even if I just cast the number to float and back again (see "Uncomment this..." in the above code), then the correct 8 bytes are written.
I am compiling with MinGW GCC-6.3.0-1. What am I doing wrong?