I am tyring to use stucts with binary files in C. I read in a file of structs of people. Each person has an attribute is_a_winner, is_runner_up if is_a_winner is true I should add Gold in the Prize field, if is_runner_up is true, add Silver otherwise add bronze. It works on some structs but not others. I think it may be to do with the positioning of the ‘cursor’ in the file.
struct prizelist{
char name[10];
int is_a_winner;
int is_runner_up;
int age;
char prize[20];
};
void addPrize() {
FILE *fp;
if ((fp = fopen("prize.out", "rb+"))!=NULL) {
size_t itemSize = sizeof(struct prizelist);
struct prizelist item;
fread(&item,1,itemSize, fp);
while (!feof(fp)) {
if (item.is_a_winner) {
strcpy( item.prize, "Gold" );
} else if (item.is_runner_up) {
strcpy( item.prize, "Silver" );
} else {
strcpy( item.prize, "Bronze" );
}
fseek(fp, itemSize, SEEK_CUR);
fwrite(&item, itemSize, 1, fp);
fread(&item,1,itemSize, fp);
}
fclose(fp);
}
}
Your code as presented can be boiled down to:
The problem is in your fseek() call; you are doing a relative seek from your current (
SEEK_CUR) position forward in the file and then writing to it… if I understand your intention to be to update the record you just read, you’ve seeked in the wrong direction. If your first record was record 0, your position after the read is at record 1, then you seek to record 2, and then you write. Whoops! Instead, seek with:fseek(fp, -itemSize, SEEK_CUR);to move backwards.