将结构对象数组写入文件并读取它
Writing an array of structure objects to file & reading it
我创建了一个结构对象数组,我想将它保存到一个二进制文件中。然后我再次读取文件并填充结构,但是我得到的所有值都是空的。
typedef struct {
int a;
long b;
}test;
int main(void) {
test *o1;
test *o2;
int no_of_obj = 3,i;
o1 = malloc(no_of_obj * sizeof(test));
printf("fsdfsdf");
o1[0].a = 11;
o1[0].b = 12;
o1[1].a = 21;
o1[1].b = 22;
o1[2].a = 31;
o1[2].b = 32;
for(i=0;i<no_of_obj;i++) {
printf("%d %lu\n",o1[i].a,o1[i].b);
}
FILE *F = fopen("test.db","wb");
for(i=0;i<no_of_obj;i++) {
fwrite(&o1[i],sizeof(test),1,F);
}
fclose(F);
printf("dfsdfds");
F = fopen("test.db","rb");
if(!F) {
printf("no file!");
return 0;
}
fseek(F,0,SEEK_END);
int size = ftell(F);
int total_objects = size/sizeof(test);
o2 = malloc(sizeof(test) * total_objects);
for(i=0;i<total_objects;i++) {
fread(&o2[i],sizeof(test),1,F);
}
for(i=0;i<total_objects;i++) {
printf("%d %lu\n",o2[i].a,o2[i].b);
}
return 0;
}
当您调用 fseek(F,0,SEEK_END);
you are moving the position indicator to the end of the file. You need to move back to the start of the file before you call fread()
(after you call ftell()
获取尺寸时)因为它从指标的当前位置开始读取。
您可以使用 fseek(F,0,SEEK_SET);
或 rewind(F);
执行此操作 - 它们具有相同的效果。
如果您检查 fread()
的 return 值,您会早点注意到这一点,因为它 return 是成功读取的字节数。 feof()
and ferror()
也很重要。
我创建了一个结构对象数组,我想将它保存到一个二进制文件中。然后我再次读取文件并填充结构,但是我得到的所有值都是空的。
typedef struct {
int a;
long b;
}test;
int main(void) {
test *o1;
test *o2;
int no_of_obj = 3,i;
o1 = malloc(no_of_obj * sizeof(test));
printf("fsdfsdf");
o1[0].a = 11;
o1[0].b = 12;
o1[1].a = 21;
o1[1].b = 22;
o1[2].a = 31;
o1[2].b = 32;
for(i=0;i<no_of_obj;i++) {
printf("%d %lu\n",o1[i].a,o1[i].b);
}
FILE *F = fopen("test.db","wb");
for(i=0;i<no_of_obj;i++) {
fwrite(&o1[i],sizeof(test),1,F);
}
fclose(F);
printf("dfsdfds");
F = fopen("test.db","rb");
if(!F) {
printf("no file!");
return 0;
}
fseek(F,0,SEEK_END);
int size = ftell(F);
int total_objects = size/sizeof(test);
o2 = malloc(sizeof(test) * total_objects);
for(i=0;i<total_objects;i++) {
fread(&o2[i],sizeof(test),1,F);
}
for(i=0;i<total_objects;i++) {
printf("%d %lu\n",o2[i].a,o2[i].b);
}
return 0;
}
当您调用 fseek(F,0,SEEK_END);
you are moving the position indicator to the end of the file. You need to move back to the start of the file before you call fread()
(after you call ftell()
获取尺寸时)因为它从指标的当前位置开始读取。
您可以使用 fseek(F,0,SEEK_SET);
或 rewind(F);
执行此操作 - 它们具有相同的效果。
如果您检查 fread()
的 return 值,您会早点注意到这一点,因为它 return 是成功读取的字节数。 feof()
and ferror()
也很重要。