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
+11.6k Golang : Concatenate (combine) buffer data example
+20k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+7.9k Golang : Load DSA public key from file example
+7.7k Gogland : Single File versus Go Application Run Configurations
+18.7k Golang : Send email with attachment
+14.9k Golang : Normalize unicode strings for comparison purpose
+18.7k Golang : Set, Get and List environment variables
+17.1k Golang : How to save log messages to file?
+10.6k Generate Random number with math/rand in Go
+6.2k Fix ERROR 2003 (HY000): Can't connect to MySQL server on 'IP address' (111)
+7.8k Android Studio : AlertDialog to get user attention example
+11.2k How to test Facebook App on localhost ?