Question

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.

Was it helpful?

Solution

The C++ istream methods you need for this are seekg and read.

// Seek and read record 2
fbook.seekg(byteNum(2));
fbook.read((char*)&book, sizeof(book));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top