分页: 1 / 1

[疑问]C语言结构体(包含不同类型)保存到文件的问题

发表于 : 2016年10月20日 22:04
newbie
比如有个结构体是这样的

代码: 全选

#include <stdio.h>

struct myst {
    short i;
    long c;
    short j;
};
 
int main(void) {
    FILE *fp;
    fp = fopen("test.txt", "wb");

    struct myst ins = {0xaa, 0xbb, 0xcc};

    printf("size:%d\n", sizeof(ins));
    fwrite(&ins, sizeof(ins), 1, fp); 
    fclose(fp);
    return 0;
}
但是写出的文本用十六进制查看却是这样的
aa00 4800 bb00 0000 cc00 0000
其中 4800 可能变成其他数值。

Re: [疑问]C语言结构体(包含不同类型)保存到文件的问题

发表于 : 2016年10月24日 23:27
paktc
参考链接: http://www.cplusplus.com/forum/beginner/32688/
Shredded 写了:to pack your structure into 18 bytes you will need to use the pragma pack statements
#pragma pack(push, 1)

typedef struct hd_fileheader
{
unsigned long long magic;
unsigned short hdata_version;
key_num next_key_num;
}

#pragma pack(pop)
The value of magic is reversed because of the way the computer stores integers. etc.
look up
Little Endian
if you want to find out why.

Hope this has been helpful
Shredded