Okay, I'll be the first to admit that I'm in a little bit over my head here.
Got this assignment from school where we're supposed to read from/write to a binary file, more precisely an index covering name, age and weight.
We are supposed to use structs and arrays to accomplish this task.
I can not make any sense of this, and have no idea how to get fread to work.
when I printf the values (e.g. personinfo[0].name) it's all nonsense.
Am I totally confused in my coding, or is there some sense in it?
Any help would be very much appreciated, since my teacher is on vacation.
Code:
#include <stdio.h>
#include <string.h>
struct personinfo
{
char name[30];
int age[3];
float weight[5];
};
int main (void) {
int i,j;
printf("How many entries?\n");
scanf("%d",&j);
FILE *fp;
fp=fopen("data.bin", "rb");
struct personinfo person[4];
i=0;
for (i=0;i<j;i++){
printf("Name:\n");
scanf("%s",person[i].name);
fwrite(person[i].name,sizeof(struct personinfo),sizeof(i),fp);
printf("Age:\n");
scanf("%d",person[i].age);
fwrite(person[i].age,sizeof(struct personinfo),sizeof(i),fp);
printf("Weight:\n");
scanf("%f",person[i].weight);
fwrite(person[i].weight,sizeof(struct personinfo),sizeof(i),fp);
}
i=0;
for (i=0;i<j;i++){
fread(person[i].name,sizeof(struct personinfo),sizeof(i),fp);
fread(person[i].age,sizeof(struct personinfo),sizeof(i),fp);
fread(person[i].weight,sizeof(struct personinfo),sizeof(i),fp);
}
fclose(fp);
}