如何从二进制文件中查找和读取

How to seek and read from binary file?

本文关键字:查找 读取 二进制文件      更新时间:2023-10-16

我对高级文件和结构还是个新手。我只是很难弄清楚如何从文件中查找和读取特定记录。以及如何通过记录编号显示特定记录的信息?

    #include <iostream>
    #include <fstream>
    using namespace std;
struct catalog
{
  char title[50];
  char author[50];
  char publisher[30];
  int yearpublish;
  double price;
};
void showRec(catalog);
long byteNum(int);
int main()
{
  catalog book;
  fstream fbook("book.dat",ios::in|ios::binary);
  if (!fbook)
  {
    cout <<"Error opening file";
    return 0;
  }
  //Seek and read record 2 (the third record)

  showRec(book);  // Display record 2
  //Seek and read record 0 (the first record)

  showRec(book); // Display record 0
  fbook.close();
  return 0;
}
 void showRec(catalog record)
 {
    cout << "Title:" << record.title << endl;
    cout << "Author:" << record.author << endl;
    cout << "Publisher name:" << record.publisher << endl;
    cout << "Year publish:" << record.yearpublish << endl;
    cout << "Price:" << record.price << endl << endl;
 }
long byteNum(int recNum)
{
 return sizeof(catalog) * recNum;
 }

请帮忙。非常感谢。

您需要的C++istream方法是seekgread

// Seek and read record 2
fbook.seekg(byteNum(2));
fbook.read((char*)&book, sizeof(book));