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
Syntax – There are two syntax for
seekg() in file handling :
istream&seekg(streamoff offset, ios_base::seekdir dir);
- position : is the new position in the stream buffer.
- offset : is an integer value of type streamoff representing the offset in the stream’s buffer. It is relative to the dir parameter.
- dir : is the seeking direction. It is an object of type ios_base::seekdir that can take any of the following constant values.
There are 3 direction we use for offset value :
ios_base::beg(offset from the beginning of the stream’s buffer).
ios_base::cur(offset from the current position in the stream’s buffer).
ios_base::end(offset from the end of the stream’s buffer).
If we previously get an end of file on the stream, seekg will not reset it but will return an error in many implementations. – use the
clear() method to clear the end of file bit first. This is a relatively common mistake and if
seekg() is not performing as expected.
This article is contributed by Shivani Baghel. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Read a record from a File in C++ using seekg() and tellg()
- Four File Handling Hacks which every C/C++ Programmer should know
- tellp() in file handling with c++ with example
- File Handling through C++ Classes
- C program to copy contents of one file to another file
- fopen() for an existing file in write mode
- 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
- Write a C program that displays contents of a given file like 'more' utility in Linux
- C Program to count number of lines in a file
- C Program to print contents of file
- C Program to merge contents of two files into a third file
- C program to delete a file
- C++ program to print unique words in a file
- Understanding ShellExecute function and it's application to open a list of URLs present in a file using C++ code
- Find sum of integers in a file which contains any characters
- C++ program to read file word by word
- C++ program to append content of one text file to another
- Program to delete a line given the line number from a file
- C Program to find size of a File