cbse 2017 question

closed account (1vf9z8AR)
I am not able to figure out how to calculate the answer.Its really confusing as we rarely use these commands in practical and read this only in theory.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
Find the output of the following C++ code considering that the binary file
BOOK.DAT exists on the hard disk with a data of 200 books.
class BOOK
{
int BID;char BName[20];
public:
void Enter();void Display();
};
void main()
{
fstream InFile;
InFile.open("BOOK.DAT",ios::binary|ios::in);
BOOK B;
InFile.seekg(5*sizeof(B));
InFile.read((char*)&B, sizeof(B));
cout<<"Book Number:"<<InFile.tellg()/sizeof(B) + 1;
InFile.seekg(0,ios::end);
cout<<" of "<<InFile.tellg()/sizeof(B)<<endl;
InFile.close();
}


Ans ​Book Number: 7 of 200
Lines 11 and 12 open an file stream attached to file "BOOK.DAT" for binary (straight bytes, no formatting) read.

Line 13 creates an object B of class BOOK.

In line 14, sizeof(B) is the size in bytes of one BOOK. 5*sizeof(B) is the size in bytes of 5 books. The seekg(pos) command moves to an absolute position pos in the filestream. Thus, if the 0th position of the stream was the start of the first book, it will now be positioned at the start of the 6th book.

Line 15 reads a further BOOK-worth of bytes from the file (so it reads the sixth book into the object B); tellg() will point at the start of the 7th book

On the basis of what you did on lines 14 and 15, tellg()/sizeof(B) will be 6 (i.e. 5 from the initial positioning, another 1 from the read) and thus on line 16,
tellg()/sizeof(B) + 1 will be 6+1 = 7.
Basically, you are pointing at the start of the 7th book at this instant.

Line 17 moves forward to 0 bytes offset from the end of the file (ios::end) - this uses the two-parameter overload of seekg().

Line 18 tellg() gives the byte count at the end of the file, so tellg()/sizeof(B) tells you how many books this is (200 in this instance).


Overall:
seekg() positions you in an (input) filestream;
tellg() gives you the current position (for input) in bytes;
sizeof() tells you how many bytes are needed for each object.

Thus,
tellg()/sizeof(thing)
will tell you how many "things" you are through the file.

http://www.cplusplus.com/reference/istream/istream/seekg/
http://www.cplusplus.com/reference/istream/istream/tellg/



Last edited on
closed account (1vf9z8AR)
omg thankyou. It looks so easy now. :)
Topic archived. No new replies allowed.