So, this is the question given in my book .
It is to read the following code and answere the question given below:
#include<fstream.h>
class Book
{
int Bno;char title[20];
public:
void Enterval()
{
cin>>Bno;
cin.getline(title,20);
}
void ShowVal()
{
cout<<Bno<<"#"<<title<<endl;
}
};
void Search(int Recno)
{
fstream file;
Book B;
file.open("BOOKS.DAT",ios ::binary|ios :: in);
______________// statement 1
file.read((char*)& B,sizeof(B));
B.ShowVal();
file.close();
}
1) to place the file pointer to the beginning of the desired record to be read , which is sent as parameter of the function(assuming RecNo 1 stands for the first record).
the answer given is
file.seekg((RecNo-1)*sizeof(B));
i just want to know why they've written (RecNo-1). Is the file pointer at the end of the file when it has been opened and is it pointing to the beginning of the record.
Also i want to know if the answer could be
file.seekg(-1*sizeof(B),ios::cur);
since we have to read from the beginning of the reord.
please tell me if i'm right and correct me if wrong.
Help appreciated.
Thankyou!
The file pointer will be at the begining of a file when it is opened.
For the Nth record the statement would be
file.seekg((N-1)*sizeof(B));
This is because to view or edit the Nth record, you have to move your pointer to the end of the N-1 record and then read it, which is what the above mentioned code does.
What you have proposed
file.seekg(-1*sizeof(B),ios::cur);
Will not work as you have just opened your file and are trying to go to a position that exists before the first position in the file which is impossible, So this code will not work.
Hope this solves your questions