Golang bytes.Reader.Seek() function example
package bytes
Seek sets the offset for the next Read or Write to offset, interpreted according to whence: 0 means relative to the origin of the file, 1 means relative to the current offset, and 2 means relative to the end. Seek returns the new offset and an error, if any.
Seeking to a negative offset is an error. Seeking to any positive offset is legal, but the behavior of subsequent I/O operations on the underlying object is implementation-dependent.
Golang bytes.Reader.Seek() function usage example
package main
import (
"bytes"
"fmt"
)
var str = []byte("abcdef")
func seekorigin() {
fmt.Println("Origin:")
b := bytes.NewReader(str)
fmt.Println(b.Seek(1, 0)) //0 means relative to the origin of the file
c, _ := b.ReadByte()
fmt.Println(string(c))
}
func seekcurrent() {
fmt.Println("Current:")
b := bytes.NewReader(str)
b.ReadByte() // read next byte
b.ReadByte() // read another byte
fmt.Println(b.Seek(1, 1)) // 1 means relative to the current offset
c, _ := b.ReadByte()
fmt.Println(string(c))
}
func seekend() {
fmt.Println("End:")
b := bytes.NewReader(str)
fmt.Println(b.Seek(-2, 2)) //2 means relative to the end
c, _ := b.ReadByte()
fmt.Println(string(c))
}
func main() {
seekorigin()
seekcurrent()
seekend()
}
Output :
Origin:
1 <nil>
b
Current:
3 <nil>
d
End:
4 <nil>
e
Reference :
Advertisement
Something interesting
Tutorials
+13.7k Golang : Check if an integer is negative or positive
+5k Google : Block or disable caching of your website content
+6.2k Golang : Extract XML attribute data with attr field tag example
+19k Golang : Padding data for encryption and un-padding data for decryption
+23.5k Golang : Read a file into an array or slice example
+30.5k Get client IP Address in Go
+5.3k Golang : Get FX sentiment from website example
+9.6k Javascript : Read/parse JSON data from HTTP response
+5.3k Golang : How to deal with configuration data?
+8.7k Golang : How to join strings?
+10.2k Golang : Bcrypting password