我是一名CS学生,我正在尝试理解一段代码,但我无法绕过它。这段代码允许用户修改二进制文件中的某个记录(结构)。我不明白records.seekg(recNum * sizeof(person), ios::beg); and records.seekp(recNum * sizeof(person), ios::beg);
。为什么rec num使用结构大小的指针。任何帮助是极大的赞赏。
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();
}
答案 0 :(得分:0)
它没有指向大小的指针,星号只是一个乘法。它将索引乘以存储在文件中的元素的大小。
例如,如果每个记录是20个字节,那么第一个记录将在偏移0处,第二个记录在偏移量20处,然后是40,60等。