【问题标题】:Understanding Seekg() and seekp() when dealing with binary files在处理二进制文件时理解 Seekg() 和 seekp()
【发布时间】:2014-12-16 19:17:32
【问题描述】:

我是一名 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();
}

【问题讨论】:

  • seek 函数采用偏移量,在这种情况下从文件的开头 (ios::beg)。并且这个偏移量是recordNum乘以记录的字节大小(即sizeof(person))(参见seekpseekg的文档)

标签: c++ ios seekg


【解决方案1】:

它没有指向大小的指针,星号只是一个乘法。它将索引乘以文件中存储的元素的大小。

例如,如果每条记录是 20 字节,那么第一条记录的偏移量为 0,第二条记录的偏移量为 20,然后是 40、60 等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-18
    • 2012-12-29
    • 1970-01-01
    • 1970-01-01
    • 2012-01-31
    • 2013-06-13
    • 2011-04-05
    相关资源
    最近更新 更多