user3566683
user3566683

Reputation: 5

Understanding Seekg() and seekp() when dealing with binary files

I am a CS student, and I am trying to understand a piece of code but I can't wrap my head around it. This piece of code allows the user to modify a certain record(structure) in a binary file. I don't understand records.seekg(recNum * sizeof(person), ios::beg); and records.seekp(recNum * sizeof(person), ios::beg);. Why is the rec num using the pointer of the size of the structure. Any help is greatly appreciated.

void modify()
{
    int recNum;

    displayAll();

    fstream records("records.dat", ios::in | ios::out | ios::binary);   
    //get record number of the desired record.
    cout << "Which record do you want to edit? ";
    cin >> recNum;

    recNum = recNum - 1;

    records.seekg(recNum * sizeof(person), ios::beg);
    records.read(reinterpret_cast<char *>(&person), sizeof(person));

    cout << "ID   Age " << " " << "Name" << setw (28) << right << "Phone\n";

    cout << person.id << "  " << left << setw(20) << person.name << right << setw(20) << person.phone << endl;

    //Get new record data.
    cout << "\nEnter the new data:\n";
    cout << "Id: ";
    cin >> person.id;

    cin.ignore();
    cout << "Name: ";
    cin.getline(person.name, NAME_SIZE);

    cout << "Age: ";
    cin >> person.age;

    cin.ignore();
    cout << "Phone: ";
    cin.getline(person.phone, PHONE_SIZE);

    records.seekp(recNum * sizeof(person), ios::beg);
    records.write(reinterpret_cast<char *>(&person),sizeof(person));
    records.close();
}

Upvotes: 0

Views: 3144

Answers (1)

John Stephen
John Stephen

Reputation: 7734

It isn't taking a pointer to the size, that asterisk is just a multiply. It's multiplying the index by the size of the elements stored in the file.

For example, if each record is 20 bytes, then the first record will be at offset 0, the second at offset 20, then 40, 60, etc.

Upvotes: 0

Related Questions