首页 > 其他分享 >ReadWriteStruct

ReadWriteStruct

时间:2023-06-18 11:02:37浏览次数:29  
标签:Node ch int ReadWriteStruct second sizeof first


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

typedef struct node {
        int x;//4:0~3 [4567]
        double y;//8:8~15
        char ch;//1:16~ [...]
} Node;//24

int main(void)
{

        Node first;
        Node second;
        FILE * wt,*rd;

        first.x = 10;
        first.y = 0.1;
        first.ch = 'a';
		{
			printf("sizeof(first):%d\nfirst:%x,first.x:%x\nfirst.y offset:%d\nfirst.ch offset:%d\n",
				    sizeof(first)      ,&first, &first.x,   (int)&first.y-(int)&first, (int)&first.ch-(int)&first     );
		}
        if ((wt = fopen("temp.bin", "w+b")) == NULL) {
                perror("Memory allocate!\n");
                exit(EXIT_FAILURE);
        }
        fwrite(&first, sizeof(Node), 1, wt);
        fclose(wt);
        
	    if ((rd = fopen("temp.bin", "r+b")) == NULL) {
        perror("Memory allocate!\n");
        exit(EXIT_FAILURE);
        }
        fread(&second, sizeof(Node), 1, rd);
        printf("%d %f %c\n", second.x, second.y, second.ch);

        fclose(rd);

        return 0;
}
/*
sizeof(first):24
first:12ff68,first.x:12ff68
first.y offset:8
first.ch offset:16
10 0.100000 a
Press any key to continue
*/


ReadWriteStruct_#include


标签:Node,ch,int,ReadWriteStruct,second,sizeof,first
From: https://blog.51cto.com/gjwrxz/6507749

相关文章