Im currently trying to delete a record from a file
The structure ive used is this:
struct studentRecord
{
char rollnumber[12];
char name[32];
int attendancePercentage;
float quiz;
float assignment;
int classpart;
float mid1;
float mid2;
float final;
float semesterPerformance;
float overallPerformance;
};
Now I have 2 problems:
1.I cant copy the name of 1 record to another
2. if i comment the name and roll number the file that is rewritten does not contain ANY data.
ANY kind of help would be greatly appreciated, i have been stuck on this for the past 2 hours
Here is my code
//Function for deleting a record
void deleteRecord(char filename[])
{
char choice ='y';
cout <<endl<<endl;
cout <<"Please enter the roll number or Name of the student for the \nRecord to be deleted" <<endl;
char searchWord[32];
gets (searchWord);
gets (searchWord);
int RecordNum = searchDisplay("Student Records.bin", searchWord); //Returns the record number to be deleted
cout<<endl<<endl<<"DO U WISH TO DELETE THIS RECORD? Y/N" <<endl;
cin >> choice;
if (choice == 'y' || choice =='Y')
{
//We first load all the file data to the Memory
FILE *inFile;
inFile = fopen("Student Records.bin" , "a+");
if (inFile == NULL) {
printf("Cannot open %s\n", filename);
exit(8);
}
int noRecords = NumberRecords("Student Records.bin");
studentRecord* Record;
Record = (studentRecord *) malloc(noRecords*sizeof(studentRecord));
if (Record == NULL) {fputs ("Memory error",stderr); exit (2);}
for(int j=0; j < noRecords;j++)
{
fread((void*)&Record[j].rollnumber , sizeof(studentRecord), 1, inFile);
}
//Then we swap records untill last record has been reached.
for (int x=0; x <= (noRecords-RecordNum);x++)
{
//last record cant be swapped so we insert a check
if(noRecords == RecordNum)
break;
/*strcpy_s ( Record[RecordNum + x].name, Record[RecordNum + (x+1)].name );
strcpy_s ( Record[RecordNum + x].rollnumber, Record[RecordNum + (x+1)].rollnumber );*/
Record[RecordNum + x].attendancePercentage = Record[RecordNum + (x+1)].attendancePercentage;
Record[RecordNum + x].quiz = Record[RecordNum + (x+1)].quiz;
Record[RecordNum + x].assignment = Record[RecordNum + (x+1)].assignment;
Record[RecordNum + x].classpart= Record[RecordNum + (x+1)].classpart;
Record[RecordNum + x].mid1= Record[RecordNum + (x+1)].mid1;
Record[RecordNum + x].mid2= Record[RecordNum + (x+1)].mid2;
Record[RecordNum + x].final= Record[RecordNum + (x+1)].final;
Record[RecordNum + x].semesterPerformance= Record[RecordNum + (x+1)].semesterPerformance;
Record[RecordNum + x].overallPerformance= Record[RecordNum + (x+1)].overallPerformance;
}
//Now we rewrite all our data back to the file.
FILE *infile;
infile = fopen("Student Records.bin" , "w");
if (infile == NULL) {
printf("Cannot open %s\n", filename);
exit(8);}
for(int f=0; f < noRecords - 1; f++)
{
fwrite((void*)&Record[f].rollnumber , sizeof(studentRecord), 1, inFile);
}
fclose(inFile);
free(Record);
}
}