我有一个列出学生的程序,它可以添加新学生,通过学生编号从列表中搜索甚至删除学生,它包含一个学生信息结构。所有信息都在一个名为 REG.DAT 的文件中。我的问题出在 >>DELETE<< 部分。我想按学生编号从列表中删除一个学生,但是当我这样做时,我将列表的其余部分丢失给必须删除的人。请帮我解决这个问题。这是我的代码:
void _remove()
{
int std_num = 0 , k ;
int status = 1 , i = -1 , j = 0 ;
struct students read[100] ,temp;
FILE *p ;
p = fopen("reg.dat","rb");
if(!p)
{
system("cls");
cout << ">>>>>Register file could not be opened! call the support .<<<<<" << endl;
_menu();
}
while(!feof(p))
{
fread(&read[i],sizeof(struct students),1,p) ;
i++;
}
cout << "Enter STD NO. to delete from the list : " << endl ;
cin >> std_num ;
for( j = 0 ; j < i ; j++)
{
if(std_num == read[j].std_num)
{
for( k = j + 1 ; k < i ; k++)
{
memcpy(&read[k-1] , &read[k],sizeof (students));
}
}
}
fclose(p);
FILE *fp;
fp = fopen("reg.dat","wb");
for( int l = 0 ; l < i - 2 ; l++)
fwrite(&read[l], sizeof(struct students), 1 ,fp );
fclose(fp);
system("cls") ;
cout << "STD with NO. " << std_num << " has been removed" << endl ;
_menu();
}