radiantshaw
radiantshaw

Reputation: 545

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

So this is my code to "Modify a record from a binary file", and it should work...

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...\n\n";
    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();
}

But the problem with this code is that it does not modifies any record... Why?

Upvotes: 0

Views: 1519

Answers (1)

Tim
Tim

Reputation: 5389

You should add a debug statement inside of if(temp.retRollNo() == RollNo), something like cout << "Made it here\n";

After reading this link I think you really should be passing std::fstream::in | std::fstream::out as the second argument to file.open() .

Upvotes: 2

Related Questions