user2044676
user2044676

Reputation: 11

Overwriting a field in a binary file

I'm writing a program that writes structs to a binary file, and then gives the user the option to edit the file. The program should then rewrite that section in the file where the original struct was written. Code:

struct Record
{
    char name     [16];
    char phoneNum [16];
    float balance;
};

int edit     ( fstream& ref)
{
    char searchVal[16];
    cout << "Enter customer name: ";
    cin.ignore();
    cin.getline(searchVal, sizeof(searchVal));
    int position = -1;
    Record buffer;
    bool found = false;

    while(!ref.eof() && !found)
    {
        position = ref.tellg();
        ref.read(reinterpret_cast<char*>(&buffer), RECORD_SIZE);
        if((strcmp(buffer.name,searchVal) == 0))
        {
            found = true;

            cout << buffer.name << " found! " << endl;

            cout << "Enter new customer name: ";
            cin.getline(buffer.name, sizeof(buffer.name));
            cout << "Enter new customer phone number: ";
            cin.getline(buffer.phoneNum, sizeof(buffer.phoneNum));
            cout << "Enter new customer balance: ";
            cin >> buffer.balance;

            ref.seekg(-(RECORD_SIZE), ios::cur);
            ref.write(reinterpret_cast<char*>(&buffer), RECORD_SIZE);

            position = ref.tellp();
            break;
        }
    }   
    if(!found)
    {
        cout << "Record not found" << endl;
    }

    ref.clear();
    ref.seekg(0L, ios::beg);
    return position;
}

BAsically, the record is found and the user can "edit" it, but it is written at the end of the file, and I'm not sure why. I appreciate your help on this.

Upvotes: 1

Views: 1142

Answers (1)

Barmar
Barmar

Reputation: 780663

Don't use the mode ios::app when opening the file. This mode means that output should append to the file instead of overwriting. Instead, use ios::ate, which tells it to seek to the end of the file when the file is opened, so it won't truncate.

Upvotes: 1

Related Questions