我需要编写一些将双精度写入文件的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);
,或者即使我只是将数字转换为浮动并再次返回(请参阅上面代码中的“取消注释...”),则会写入正确的8个字节。
我正在使用MinGW GCC-6.3.0-1进行编译。我究竟做错了什么?
您以文本模式打开文件,并正在向其写入二进制数据。 Windows将LF 0x0a
更改为CRLF 0x0d 0x0a
。打开文件时,需要使用“wb”作为第二个参数。