[英]How to read/write nested structure to file c?
我想将嵌套结构存储到 a.dat 文件中,并在需要时在另一个文件中读取它。
它说“读取文件时出现分段错误(核心已转储)。
我该如何解决这个问题???
这些是结构:
struct address {
int code;
char city[10];
};
struct student {
char name[10];
struct address *ads;
};
这是写的代码:
struct student *person;
if((person = malloc(sizeof(*person))) == NULL) {
printf("cannot allocate memory\n");
return -1;
}
strcpy(person->name, "s1");
if((person->ads = malloc(sizeof(*(person->ads)))) == NULL) {
printf("cannot allocate memory to address\n");
free(person);
return -1;
}
person->ads->code = 1;
strcpy(person->ads->city, "mumbai");
FILE *file;
if((file = fopen("file.dat", "wb")) == NULL) {
printf("Could not open file.dat\n");
free(person->ads);
free(person);
return -1;
}
fwrite(&person, sizeof(*person), 1, file);
if(fwrite) {
printf("written\n");
}else{
printf("not written\n");
}
fclose(file);
这是阅读代码:
struct student *person;
FILE *file;
if((file = fopen("file.dat", "rb")) == NULL) {
printf("Could not open file.dat\n");
free(person);
return -1;
}
fread(&person, sizeof(*person), 1, file);
printf("cityname: %s\n", person->ads->city);
fclose(file);
struct address
没有“嵌套”在struct student
中; struct student
包含一个指针,而不是嵌套结构。
不能用write
有意义地写入指针:您可以这样做,但结果仅在指向的 object 的生命周期内,并且仅在 object 存在的进程中才有意义。 将数据写入外部文件的目的通常是允许它在不确定的未来和另一个进程中使用,这两者对于指针来说都不是真的。
如果要将 object 之类的struct address
写入持久存储,则必须对数据进行序列化:即将其转换为可以写入多个对象并明确指示它们之间关系的格式。 您会发现许多序列化框架只要稍微研究一下这个术语,但这种情况对于直接实施来说可能足够简单。 毫无疑问,这就是这项家庭作业的重点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.