Reading\Writing 包含 char 和 float 的二进制文件

Reading\Writing Binary File with char's and float's

我是 C 的新手,就像标题所说的那样,我正在尝试编写一个简单的程序来读写二进制文件。代码如下:

#include<stdio.h>

int main(void){

    FILE *fd = fopen("binFile.bin", "wb");

    if(fd == NULL){
        printf("Failed to open/create file.\n");
        return -1;
    }

    char buff1[] = "#This is a comment.\n";
    fwrite(buff1,1,sizeof(buff1),fd);
    char buff2[] = "#This is another comment.\n";
    fwrite(buff2,1,sizeof(buff2),fd);

    int i;
    float f[3];

    for(i=0; i<100; i++){
        f[0] = i-1;
        f[1] = i;
        f[2] = i+1;

        fwrite(f,sizeof(f),1,fd);
    }

    fclose(fd);

    fd = fopen("binFile.bin", "rb");

    if(fd == NULL){
        printf("Failed to read file.\n");
        return -1;
    }

    char buff[100];

    do{
        fread(buff,1,sizeof(buff),fd);
        printf("%s",buff);
    }
    while(!feof(fd));

    fclose(fd);

    return 0;
}

当我 运行 这段代码时,它只打印:

#This is a comment.

我知道我没有对文件使用一堆检查;但是,我认为问题在于我正在尝试使用相同的缓冲区读取 char 和 float,因为仅对 char(或仅 float)使用相同的代码工作得很好。我猜我必须以某种方式知道 char 的字节和浮点数的字节在哪里开始相应地调整我的缓冲区 size/type。

我希望我能充分解释自己。任何帮助表示赞赏。

看看你的二进制文件

如您所见,字节 14h 处有一个空终止符,就在“This is a comment.\n”字符串之后.

这是因为您在使用字符串文字初始化的 char 数组上使用 sizeof(buff1),此类文字始终包含空终止符

另请注意您存储的浮点数是二进制格式,如果您的系统使用 IEEE754(我的也是),当您编写 -1 编码为 0bf800000h.
这导致文件中的字节值为 0,这些字节也将被解释为空终止符。