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

Cplusplus
回复
newbie
初来炸道
初来炸道
帖子: 2
注册时间: 2016年10月20日 21:57
联系:

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

帖子 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 可能变成其他数值。
头像
paktc
出类拔萃
出类拔萃
帖子: 65
注册时间: 2016年07月21日 20:34
联系:

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

帖子 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
回复

在线用户

正浏览此版面之用户: 没有注册用户 和 1 访客