代码不适用于"Modifying a data in a Binary file"

Code not working for "Modifying a data in a Binary file"

本文关键字:in Binary file data Modifying 不适用 适用于 代码      更新时间:2023-10-16

,所以这是我的代码"从二进制文件中修改记录",它应该起作用...

void Update()
{
    fstream file;
    STUDENT st, temp; // STUDENT is a class which I made
    int RollNo;
    clrscr();
    cout << "Enter the Roll Number: ";
    cin >> RollNo; // to get the roll number which is to be modified. Also there is a data member inside the class STUDENT which is also known as RollNo
    cout << "n Enter the update info...nn";
    st.Input(); // This is a function inside the class STUDENT to get the values for the data members
    file.open("Student.dat", ios::binary | ios::ate);
    file.seekg(0);
    while(file)
    {
        file.read((char*)&temp, sizeof(temp)); // the data which is being read is stored inside temp
        if(temp.retRollNo() == RollNo) // since RollNo is a private data member inside the class STUDENT so I've created an accessor function which returns RollNo
        {
            file.seekp(file.tellg() - sizeof(temp));
            file.write((char*)&st, sizeof(st));
        }
    } // please note that this loop modifies all the instances which match the criteria and not just one since this while loop runs until end of file
    file.close();
}

但是此代码的问题是它不会修改任何记录...为什么?

您应该在if(temp.retRollNo() == RollNo)的内部添加一个调试语句,例如cout << "Made it heren";

阅读此链接后,我认为您确实应该将 std::fstream::in | std::fstream::out 作为file.open()的第二个参数。