0

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?

3
  • Can you show the declaration of STUDENT? Commented Feb 2, 2014 at 5:30
  • 3
    Every one of those file io operations has a return state (the stream) that should be checked. Start with that. Commented Feb 2, 2014 at 5:39
  • What parts of this work? Can you read one STUDENT record and report it to cout? Can you modify the record, and print its new values? Can you write a single STUDENT to a file? Start small and simple, then build up, testing at every step. Commented Feb 2, 2014 at 5:55

1 Answer 1

2

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() .

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.