我仍然是推进文件和结构的新手。我只是在弄清楚如何从文件中查找和读取特定记录时遇到问题。以及如何通过它的记录号显示特定记录的信息?
#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;
}
请帮助。谢谢。
答案 0 :(得分:0)
您需要的C ++ istream
方法是seekg
和read
。
// Seek and read record 2
fbook.seekg(byteNum(2));
fbook.read((char*)&book, sizeof(book));