首页 > 解决方案 > 为什么 fwrite 为某些双精度写 9 个字节?

问题描述

我需要编写一些 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 进行编译。我究竟做错了什么?

标签: cdoublefwrite

解决方案


您以文本模式打开文件,并向其中写入二进制数据。Windows 更改LF 0x0aCRLF 0x0d 0x0a. 打开文件时,您需要使用“wb”作为第二个参数。


推荐阅读