Golang os.File.Read() and Seek() functions example
package os
Golang os.File.Read() and os.File.Seek() functions usage example
NOTE : Seek is normally used for Random File Access operation, such as reading binary file defined by a struct.
package main
import (
"fmt"
"io"
"os"
)
func main() {
file, err := os.Open("binary.dat")
if err != nil {
fmt.Println(err)
return
}
defer file.Close()
// create a 1 kilo bytes buffer to keep chunks that are read
buffer := make([]byte, 1024)
// first read
n, err := file.Read(buffer)
if err != nil && err != io.EOF {
panic(err)
}
// out the buffer content
fmt.Println(string(buffer[:n]))
// start next read at where we stop..which is position 1024 bytes
// from origin
newoffset, err := file.Seek(1024, 0)
if err != nil && err != io.EOF {
panic(err)
}
// next read
fmt.Println("---------------------------------")
n, err = file.Read(buffer)
if err != nil && err != io.EOF {
panic(err)
}
// out the buffer content
fmt.Println(string(buffer[:n]))
fmt.Println("New off set : ", newoffset)
}
References :
Advertisement
Something interesting
Tutorials
+6.6k Golang : Totalize or add-up an array or slice example
+7.8k Golang : Mapping Iban to Dunging alphabets
+10.5k Golang : Meaning of omitempty in struct's field tag
+46.6k Golang : Encode image to base64 example
+9k Golang : Inject/embed Javascript before sending out to browser example
+11.6k Golang : Change date format to yyyy-mm-dd
+14.1k Golang : Google Drive API upload and rename example
+19k Golang : Read input from console line
+10.5k Golang : Simple Jawi(Yawi) to Rumi(Latin/Romanize) converter
+19.8k Golang : Archive directory with tar and gzip
+10.5k Swift : Convert (cast) String to Integer
+13.6k Golang : Strings comparison