我在将双精度数组写入和读取二进制文件时遇到问题。在某些情况下,文件的大小比预期的要大。以下代码:
int main()
{
int i, j, size=13;
FILE *fid = fopen("C:\\Group0\\Night0\\Imanti\\test.dat", "w");
double *arr = (double *)malloc(sizeof(double)* size);
for (i = 0; i < size; i++) {
arr[i] = size / (i + 1.0);
printf("%f\n", arr[i]);
}
fwrite(arr, sizeof(double), size, fid);
free(arr);
fclose(fid);
printf("\n\n");
fid = fopen("C:\\Group0\\Night0\\Imanti\\test.dat", "r");
arr = (double *)malloc(sizeof(double)* size);
fread(arr, sizeof(double), size, fid);
for (i = 0; i < size; i++) {
printf("%f\n", arr[i]);
}
free(arr);
fclose(fid);
return 0;
}
显示了我的问题的一个简单示例。例如size = 10
,如果我运行它,文件的大小为 80 字节,并且在写入和读取时数字相同。如果我用 运行它size = 13
,文件的大小是 105 字节(当它应该是 104 字节时)并且数字完全不同。案例的输出size = 13
是:
13.000000
6.500000
4.333333
3.250000
2.600000
2.166667
1.857143
1.625000
1.444444
1.300000
1.181818
1.083333
1.000000
13.000000
-6108112916776316800000000000000000000000000000000000000000000000000.000000
-6277438562204192500000000000000000000000000000000000000000000000000.000000
-6277438562204192500000000000000000000000000000000000000000000000000.000000
-6277438562204192500000000000000000000000000000000000000000000000000.000000
-6277438562204192500000000000000000000000000000000000000000000000000.000000
-6277438562204192500000000000000000000000000000000000000000000000000.000000
-6277438562204192500000000000000000000000000000000000000000000000000.000000
-6277438562204192500000000000000000000000000000000000000000000000000.000000
-6277438562204192500000000000000000000000000000000000000000000000000.000000
-6277438562204192500000000000000000000000000000000000000000000000000.000000
-6277438562204192500000000000000000000000000000000000000000000000000.000000
-6277438562204192500000000000000000000000000000000000000000000000000.000000
第一个数字 (13) 或第二个数字 (6.5) 写入了一个额外的字节,导致文件变大并且读取失败。我知道双重表示会导致精度错误,但据我所知,这与精度无关,因为文件中双变量的大小正在发生变化。
我不确定我是否在这里遗漏了一些非常明显的东西,但这已经让我发疯了。我在 i7 电脑上使用 vs2013。