unable to read struct from a binary file using C when file is not 100% filled as expected -
i have file try read contacts simple contactbook using structure.
typedef struct contact{ char name[80]; char surname[80]; char cellnumber[20]; float length; int contactid; }contact;
i use function , call reads 200 times (const int maxcontact = 200;
).
for(i2=0;i2<maxcontact;i2++) person[i2]=load(i2);
this function given id (the variabile i
), returns contact has same i:
contact load(int i){ struct contact person; file *data; data=fopen("data.bin","rb"); do{ fread(&person,sizeof(contact),1,data); }while(person.contactid!=i); fclose(data); return person; }
the problem kind of code is, when there no 200 contacts, function not return contact because contact id can't found.
i had solutions in mind rather complex , wanted know if done better.
make installer creates files real installer , create 200 undeclared contacts variabiles equal null.
check if program being ran first time , same thing above in program itself.
if contact id not found exit searching loop equally , return undecleared contact variabiles set null.
after writing this, 3 questions come mind:
which 1 of these best 1 or easiest work with?
is safe return undecleared contact? (i have keep in mind have work contacts: modefy, print, print contacts)
should have structure , file write down statistics of variabiles not used in contact structure/file?
try following approach, linear complexity, if contact absent, initialized 0.
/* initialize memory */ memset(person, 0, maxcontact * sizeof(contact0); /* open file */ data=fopen("data.bin","rb"); /* file size */ fseek(data, 0l, seek_end); /* don't read more allocated array can contain */ int size = max(ftell(data), maxcontact * sizeof(contact)); /* seek beginning of file */ fseek(fp, 0l, seek_set); /* populate array */ fread(&person,size,1,data); /* close file */ fclose(data);