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
+14.6k Golang : Missing Bazaar command
+13.1k Golang : Convert(cast) uintptr to string example
+7.2k Ubuntu : connect() to unix:/var/run/php5-fpm.sock failed (13: Permission denied) while connecting to upstream
+3.6k Java : Get FX sentiment from website example
+5.8k CodeIgniter/PHP : Remove empty lines above RSS or ATOM xml tag
+14.4k Android Studio : Use image as AlertDialog title with custom layout example
+12.6k Golang : Exit, terminating or aborting a program
+8.9k Golang : What is the default port number for connecting to MySQL/MariaDB database ?
+7.3k Golang : Not able to grep log.Println() output
+13.7k Golang : Image to ASCII art example
+29.3k Golang : Save map/struct to JSON or XML file
+18.5k Golang : Aligning strings to right, left and center with fill example