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
+5.9k Golang : Shuffle array of list
+4.7k Adding Skype actions such as call and chat into web page examples
+7.4k Golang : How to detect if a sentence ends with a punctuation?
+21.8k SSL : How to check if current certificate is sha1 or sha2
+27.7k PHP : Count number of JSON items/objects
+28.2k Golang : Connect to database (MySQL/MariaDB) server
+8.1k Golang : How To Use Panic and Recover
+12.2k Golang : Split strings into command line arguments
+9.4k Golang : Scramble and unscramble text message by randomly replacing words
+33.8k Golang : convert(cast) bytes to string
+21.9k Golang : Use TLS version 1.2 and enforce server security configuration over client
+21.2k Golang : Convert(cast) string to rune and back to string example