简体   繁体   English

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

[英]How to seek and read from binary file?

I'm still new to advance file and structures. 我还是提高文件和结构的新手。 I'm just having trouble figuring out how to seek and read specific records from a file. 我只是很难弄清楚如何从文件中查找和读取特定记录。 and how to display the information of a specific record through it's record number? 以及如何通过记录号显示特定记录的信息?

    #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;
 }

Please Help. 请帮忙。 Thank you. 谢谢。

The C++ istream methods you need for this are seekg and read . 为此所需的C ++ istream方法是seekgread

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM