I have a structure in C whose object I am writing to a file in C, while reading the same file again the last object is getting repeated two times. How can I resolve this and why is this happening?
#include<stdio.h>
#include<string.h>
typedef struct car {
int id;
char *name;
int price;
char *colors[5];
} car;
int main()
{
car obj1 = { .id = 5,
.name = "honda city zx",
.price = 1500,
.colors = {"red", "black", "blue"}
};
car obj2 = { .id = 6,
.name = "honda city",
.price = 2500,
.colors = {"lal", "kala", "neela"}
};
FILE *fp;
fp = fopen("car_details.dat", "w");
fwrite(&obj1, sizeof(obj1), 1, fp);
fwrite(&obj2, sizeof(obj2), 1, fp);
fclose(fp);
fp = fopen("car_details.dat", "r");
car obj;
while(!feof(fp))
{
fread(&obj, sizeof(obj), 1, fp);
printf("id : %d\nname : %s\nprice : %d\ncolors : {%s, %s, %s}\n", obj.id, obj.name, obj.price, obj.colors[0], obj.colors[1], obj.colors[2]);
}
return 0;
}
The output is :
id : 5
name : honda city zx
price : 1500
colors : {red, black, blue}
id : 6
name : honda city
price : 2500
colors : {lal, kala, neela}
id : 6
name : honda city
price : 2500
colors : {lal, kala, neela}
However the expected output was each object to be printed once.
id : 5
name : honda city zx
price : 1500
colors : {red, black, blue}
id : 6
name : honda city
price : 2500
colors : {lal, kala, neela}
So my question is why is this happening and how can I resolve this?
EDIT : When I tried printing the position of my pointer inside the loop
while(!feof(fp))
{
fread(&obj, sizeof(obj), 1, fp);
printf("The pointer is at %ld\n", ftell(fp));
printf("id : %d\nname : %s\nprice : %d\ncolors : {%s, %s, %s}\n\n", obj.id, obj.name, obj.price, obj.colors[0], obj.colors[1], obj.colors[2]);
}
I was getting :
The pointer is at 64
{object}
The pointer is at 128
{object}
The pointer is at 128
{object}
How is this possible? I have read that whenever fread reads the stream , it shifts the pointer after reading that much number of bytes. So when this time the loop ran for the second time it should have shifted the file pointer to the end of file but it didn't. Why is this happening? Am I lacking any concept? Please pardon me I am a beginner!