为什么 fwrite 为某些双打写入 9 个字节?
Why does fwrite write 9 bytes for some doubles?
我需要编写一些 C 代码,将双打写入文件。
对于某些值,fwrite 将正确的 8 字节二进制文件写入文件。对于其他值,它似乎在前面附加了一个额外的第 9 个字节。例如,此代码写入包含 x0d 的 9 个字节,后跟正确的 8 个字节:
#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);
}
但是,如果我更改值,例如更改为 double x = -3.0 * cos(PI * 3.0 / 8.0);
,或者即使我只是将数字转换为浮点数并再次返回(参见上面代码中的 "Uncomment this..."),那么写入了正确的 8 个字节。
我正在使用 MinGW GCC-6.3.0-1 进行编译。我做错了什么?
您以文本模式打开文件,并正在向其中写入二进制数据。 Windows 将 LF 0x0a
更改为 CRLF 0x0d 0x0a
.打开文件时需要使用 "wb" 作为第二个参数。
我需要编写一些 C 代码,将双打写入文件。
对于某些值,fwrite 将正确的 8 字节二进制文件写入文件。对于其他值,它似乎在前面附加了一个额外的第 9 个字节。例如,此代码写入包含 x0d 的 9 个字节,后跟正确的 8 个字节:
#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);
}
但是,如果我更改值,例如更改为 double x = -3.0 * cos(PI * 3.0 / 8.0);
,或者即使我只是将数字转换为浮点数并再次返回(参见上面代码中的 "Uncomment this..."),那么写入了正确的 8 个字节。
我正在使用 MinGW GCC-6.3.0-1 进行编译。我做错了什么?
您以文本模式打开文件,并正在向其中写入二进制数据。 Windows 将 LF 0x0a
更改为 CRLF 0x0d 0x0a
.打开文件时需要使用 "wb" 作为第二个参数。