I have this struct
and i also have a binary file that includes records as the above.Code:typedef struct { int salary; char id[9]; char name[12]; char surname[15]; char origin[15]; }record;
I want to make a function to delete records with the desired ID. My idea was to zero those blocks of memory and write them back to bin file, so look what i've done :
My algorithm follows those steps :Code:void SO_deleteRecord(FILE *IO) { int recsNum; char id[9]; char toCmp[recSize]; record tempRec; //Initialize rewind(IO); recsNum = 0; memset(toCmp,0,recSize); //Interface to read id printf("\n\nInsert ID : "); getStr(id,9); while(checkStr(id,ALN)) { printf("ID should be consisted of letters and numbers.\n"); printf("Insert ID : "); getStr(id,9); } puts("\n"); //Search for this record while(fread(&tempRec,1,recSize,IO) == recSize) { if((memcmp(&tempRec,toCmp,recSize) != 0)&&(strcmp(tempRec.id,id) == 0)) { //Set all block to 0 memset(&tempRec,0,recSize); //Move back one record fseek(IO,-recSize,SEEK_CUR); //Write it back to file fwrite(&tempRec,1,recSize,IO); printf("%d record with ID = %s has been deleted.\n",++recsNum,id); } } puts("\n"); //If no record found if(recsNum == 0) printf("Record with ID = %s hasn't been found.\n\n",id); }
1 While you can read from file (not EOF)
2 If record isn't empty (zero bytes)
3 Turn it to zero bytes and then
4 Move file pointer back one record (to write to the specific position)
5 Write the empty block (zero bytes) to file
The problem is in the bold text and especially is that the loop runs for ever if the record is located near the end.
If the record is located near the beginning it works fine, so i suppose the problem is the end of file.
Any ideas whats wrong ?
Thanks in advance !!



LinkBack URL
About LinkBacks



