io.SectionReader.Seek() Function in Golang with Examples
Last Updated :
05 May, 2020
In Go language, io packages supply fundamental interfaces to the I/O primitives. And its principal job is to enclose the ongoing implementations of such king of primitives. The SectionReader.Seek() function in Go language is used to find a new offset with the help of the stated offset and whence. Moreover, this function is defined under the io package. Here, you need to import the “io” package in order to use these functions.
Syntax:
func (s *SectionReader) Seek(offset int64, whence int) (int64, error)
Here, “s” is a pointer to the SectionReader which is returned by the NewSectionReader method, “offset” is of type int64, and “whence” is of type int.
Return value: It returns a new offset with the help of the given offset plus whence and also returns an error if any.
Note: There are three constant values of Seek whence, which are as follows:
- SeekStart = 0, it seeks relative to the beginning of the stated file.
- SeekCurrent = 1, it seeks relative to the latest offset of the stated file.
- SeekEnd = 2, it seeks relative to the ending of the stated file.
Example 1:
package main
import (
"fmt"
"io"
"strings"
)
func main() {
reader := strings.NewReader( "Geeks" )
r := io.NewSectionReader(reader, 1, 4)
Newoffset, err := r.Seek(6, 1)
if err != nil {
panic(err)
}
fmt.Printf( "The new offset is: %v\n" , Newoffset)
}
|
Output:
The new offset is: 6
In the above example, the value of Seek whence is 1 which means it is “SeekCurrent” so it seeks relative to the current offset.
Example 2:
package main
import (
"fmt"
"io"
"strings"
)
func main() {
reader := strings.NewReader( "Geeks" )
r := io.NewSectionReader(reader, 1, 4)
Newoffset, err := r.Seek(6, io.SeekEnd)
if err != nil {
panic(err)
}
fmt.Printf( "The new offset is: %v\n" , Newoffset)
}
|
Output:
The new offset is: 10
Here, the value of Seek whence is “SeekEnd” which means it seeks relative to the end.
Share your thoughts in the comments
Please Login to comment...