Given that a binary file “student.dat” is already loaded in the memory of the computer with the record of 100 students, the task is to read the Kth record and perform some operations.
seekg() is a function in the iostream library (part of the standard library) that allows you to seek to an arbitrary position in a file. It is used in file handling to sets the position of the next character to be extracted from the input stream from a given file. For example :
Input: "Hello World" Output: World
The tellg() function is used with input streams and returns the current “get” position of the pointer in the stream. It has no parameters and returns a value of the member type pos_type, which is an integer data type representing the current position of the get stream pointer.
Given that there are 100 records in the binary file “student.dat” and K = 7
- Step 1: The statement fs.seekg(7*sizeof(student)) places the reading pointer to 168(->7*22) index of the file (based on ‘0’ based indexing)
- Step 2:The statement fs.read((char*)this;sizeof(student)); reads the record and now the read pointer is at the starting of 8th record. Therefore the statement fs.tellg()/sizeof(s) results to value 8 and the output of “fs.tellg()/sizeof(s)+1” is 8 + 1 = 9
- Step 3: The statement fs.seekg(0, ios::end) places the pointer to the end of the file and hence fs.seekg(0, ios::end)/sizeof(s) gives 100
Below is the implementation of the above approach:
Current Position: student no: 9 of 100
- Set position with seekg() in C++ language file handling
- Implement your own tail (Read last n lines of a huge file)
- lseek() in C/C++ to read the alternate nth byte and write it in another file
- tellg() function in C++ with example
- C++ program to read file word by word
- C program to copy contents of one file to another file
- CSV file management using C++
- C++ program to create a file
- File Handling through C++ Classes
- C program to delete a file
- tellp() in file handling with c++ with example
- C Program to find size of a File
- Four File Handling Hacks which every C/C++ Programmer should know
- C Program to print contents of file
- Find sum of integers in a file which contains any characters
- Reverse the content of a file and store it in another
- Implementation of file allocation methods using vectors
- C++ program to append content of one text file to another
- C++ program to print unique words in a file
- C Program to merge contents of two files into a third file
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.