小编Xua*_*uan的帖子

为什么C用5个字节来写/写数字10,而用4个字节来写9或11?

Windows 上的 GCC

#include <stdio.h>
#include <stdlib.h>

struct test {
    int n1;
    int n2;
};

int main() {
    FILE *f;
    
    f = fopen("test.dat", "w");
    struct test test1 = {10, 10};
    fwrite(&test1, sizeof(struct test), 1, f);
    fclose(f);
    
    struct test test2;
    f = fopen("test.dat", "r");
    while(fread(&test2, sizeof(struct test), 1, f))
        printf("n1=%d n2=%d\n", test2.n1, test2.n2);
    fclose(f);
    
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

如果我将 test1 设置为,10,10则 fwrite 会将10 个字节写入文件:0D 0A 00 00 00 0D 0A 00 00 00

(每个4字节int将在其前面填充0D回车符)

如果我将 test1 设置为, …

c struct fwrite

4
推荐指数
2
解决办法
400
查看次数

标签 统计

c ×1

fwrite ×1

struct ×1