user1692342
user1692342

Reputation: 5237

Writing an array of structure objects to file & reading it

I have created an array of objects of a structure & I want to save it to a binary file. I then read the file again & populate the structure, however I am getting all the values as empty.

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;
}

Upvotes: 0

Views: 39

Answers (1)

Iskar Jarak
Iskar Jarak

Reputation: 5325

When you call 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() to get the size) because it reads from the current position of the indicator.

You can do this with fseek(F,0,SEEK_SET); or rewind(F); - they have the same effect.

You would have noticed this sooner had you checked the return value of your fread()s as it returns the number of bytes successfully read. feof() and ferror() are also important.

Upvotes: 4

Related Questions