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
+18.7k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+5.1k Golang : Convert Chinese UTF8 characters to Pin Yin
+26.8k Golang : Connect to database (MySQL/MariaDB) server
+4.2k Golang : Calculate half life decay example
+14.4k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+15.5k Golang : Merge video(OpenCV) and audio(PortAudio) into a mp4 file
+5.9k Golang : Pat multiplexer routing example
+21.1k Golang : Read a file into an array or slice example
+8.2k Golang : does not implement flag.Value (missing Set method)
+18.3k Golang : Archive directory with tar and gzip
+8.3k Golang : Changing a RGBA image number of channels with OpenCV
+11.8k Golang : Convert IPv4 address to packed 32-bit binary format