C语言中将结构体写入并读取文件

C语言中将结构体写入并读取文件

将结构体写入文件

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
    char c;
    char *str;
    char s[100];
    int h;
} st;
int main(void)
{
    FILE *fp;
    st sa, sb;
    char *str = "abcdefg";
    sa.c = 'K';
    sa.str = "abcdefg";
    strcpy(sa.s, str);
    sa.h = -3;

    fp = fopen("st.txt", "w+");
    if (!fp)
    {
        printf("errror!\n");
        exit(-1);
    }
    printf("sa:c=%c,str=%s,s=%s,h= %d\n", sa.c, sa.str, sa.s, sa.h);
    printf("sizeof(sa)=%d:&c=%x,&str=%x,&s=%x,&h=%x\n", sizeof(sa), &sa.c, &sa.str, &sa.s, &sa.h);
    fwrite(&sa, sizeof(sa), 1, fp);
    rewind(fp);
    fread(&sb, sizeof(sb), 1, fp);
    printf("sa:c=%c,str=%s,s=%s,h= %d\n", sa.c, sa.str, sa.s, sa.h);
    fclose(fp);

    return 0;
}

结果显示

sa:c=K,str=abcdefg,s=abcdefg,h= -3
sizeof(sa)=120:&c=ffffda10,&str=ffffda18,&s=ffffda20,&h=ffffda84
sa:c=K,str=abcdefg,s=abcdefg,h= -3

从文件读取结构体

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct
{
    char c;
    char *str;
    char s[100];
    int h;
} st;
int main(void)
{
    FILE *fp;
    st sb;
    fp=fopen("st.txt","r");
    if(!fp)
    {
        printf("errror!\n");
        exit(-1);
    }
    fread(&sb,sizeof(sb),1,fp);
    printf("sb:c=%c,str=%s,s=%s,h= %d\n", sb.c, sb.str, sb.s, sb.h);
    printf("sizeof(sb)=%d:&c=%x,&str=%x,&s=%x,&h=%x\n", sizeof(sb), &sb.c, &sb.str, &sb.s, &sb.h);

    fclose(fp);

    return 0;
}

结果显示

sb:c=K,str=,s=abcdefg,h= -3
sizeof(sb)=120:&c=ffffda90,&str=ffffda98,&s=ffffdaa0,&h=ffffdb04

对比结果显示

sa:c=K,str=abcdefg,s=abcdefg,h= -3
sizeof(sa)=120:&c=ffffda10,&str=ffffda18,&s=ffffda20,&h=ffffda84
sa:c=K,str=abcdefg,s=abcdefg,h= -3

结论

如果写入文件的结构体中含有指针,读取时是无法获取指针所指向的内容的,因此,最好不要用指针,可以用数组。

参考借鉴:
https://blog.csdn.net/benpaobagzb/article/details/48442777
链接: link.

你可能感兴趣的:(C语言中将结构体写入并读取文件)