Write pointer to file in C

后端 未结 7 1567
不思量自难忘°
不思量自难忘° 2020-12-19 09:32

I have a structure:

typedef struct student {
  char *name;
  char *surname;
  int age;
} Student;

I need to write the structure into a bina

相关标签:
7条回答
  • 2020-12-19 10:14

    You'll have to write out the fields individually, as others have said. One thing which may help reading back the data is to write out the string lengths before each entry, eg.

    size_t len;
    len = strlen(s->name)+1;
    fwrite(&len,sizeof(len),1,stream);
    fwrite(s->name,sizeof(*(s->name)),len,stream);
    ...
    

    Reading back is then a matter of

    Student * s = malloc(sizeof(*s));
    size_t len;
    fread(&len,sizeof(len),1,stream);
    s->name = malloc(len);
    fread(s->name,sizeof(*(s->name)),len,stream);
    ...
    
    0 讨论(0)
提交回复
热议问题