【发布时间】:2019-03-28 02:13:03
【问题描述】:
我需要编写一些 C 代码,将双精度值写入文件。
对于某些值,fwrite 将正确的 8 字节二进制文件写入文件。对于其他值,它似乎预先附加了一个额外的第 9 个字节。例如,此代码写入 9 个字节,包括 x0d,后跟正确的 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 进行编译。我做错了什么?
【问题讨论】:
-
以二进制模式打开文件。
-
@Harry man page 比谷歌搜索更可取。
-
@WeatherVane 老实说,即使在那个手册页上,访问模式修饰符也被很好地隐藏了!但你是对的,至少他们在那里。
-
@Harry 关于模式有四个段落,包括“如果 t 或 b 在 mode 中没有给出,默认翻译模式由全局变量
_fmode定义。"