更新二进制文件中的学生记录,同时删除以前的数据

Updating student record in binary file, deletes previous data aswell

本文关键字:删除 数据 记录 二进制文件 更新      更新时间:2023-10-16

我试图通过搜索他的卷号来更新学生记录,然后使用tellg((和seekp((移动到那个位置。但每当我试图覆盖时,它都会删除以前的记录。

int pos=0; 
Student obj;   
ifstream readfile("New.dat",ios::binary);
cout<<"Enter Roll # of student";       
cin>>a;
while(!readfile.eof())
{
    readfile.read((char *) &obj, sizeof(obj));
    if(obj.getRoll()==a)
    {
        if(!readfile.eof())
        {
            pos=readfile.tellg();  
            obj.show();
            cout<<"PLease Enter New Details of Student n";
            obj.get();
            readfile.close();                
            ofstream file("New.dat",ios::binary);
            file.seekp(pos);
            file.write((char*)&obj,sizeof(obj));  
            cout<<"Student Record Has Been Updated n";
            countt=1;
        }
    }
}
file.close();

在读取对象之前,您需要记录文件中的位置,这样您就可以回到同一位置再次写入对象。

pos=readfile.tellg();行移动到readfile.read行之前。