无法从C ++中删除文件中的记录

时间:2015-05-29 19:38:47

标签: c++ binary

我正在为大学编写一个小程序。我想删除已保存的员工记录。当我输入员工的ID并将其删除时,它似乎已被删除。但是当我检查记录时,它仍然存在于那里。我无法弄清楚为什么。这是代码:

system("cls");
more = 'y';
while ((more == 'y')||(more == 'Y'))
{
    faculty = fopen("Employee.txt","rb+");
    temp = fopen("temp.txt","wb+");
    rewind (faculty);
    cout<<"Employee ID: ";
    cin>>xid;
    while (fread(&em, empsize, 1, faculty) == 1)
    {
        if (xid != em.id)
        {
            fseek(temp, 0, SEEK_END);
            fwrite(&em, empsize, 1, temp);
        }
        else 
            found=1;
    }
    fclose (temp);
    fclose (faculty);
    remove ("Employee.txt");
    rename ("temp.txt", "Employee.txt");
    if (found == 1)
    {
        //faculty = fopen("Employee","rb+");
        cout<<"Delete another record (Y/N). ";
        cin>>more;
    }
    else
    {
        system("cls");
        cout<<"\n\n\t\t\t\""<<xid<<"\" ID does not Exist.\n\t\t\tDelete                    another record (Y/N). ";
        cin>>more;
    }
    if (more == 'n')
    {
        cout<<"\n\n\tTaking you back to HR .. \n\t";
        system("pause");
        HR ();
    }
}
break;

1 个答案:

答案 0 :(得分:0)

在while循环之前,您需要将found的值设置为1以外的值。如果您成功删除了一条记录,之后的所有记录删除请求都会显示成功,即使它们不是因为仍然设置了found == 1标记。