In Go, don't ignore errors. When writing to and reading from a file, keep track of the current file offset.
After the write the offset is at the end-of-file, you need to set the offset to the start-of-file before the read. For example, with diagnostic information,
package main
import (
"fmt"
"io"
"os"
)
func main() {
f1, err := os.Create("f1")
if err != nil {
fmt.Println(err)
return
}
defer f1.Close()
// The file offset is its current location.
s, err := f1.Seek(0, io.SeekCurrent)
if err != nil {
fmt.Println(s, err)
return
}
fmt.Println("offset:", s)
// writing takes place at the file offset, and
// the file offset is incremented by the number of bytes actually
// written.
n, err := f1.WriteString("some content")
fmt.Println("write: ", n, err)
if err != nil {
fmt.Println(n, err)
return
}
// The file offset is its current location
s, err = f1.Seek(0, io.SeekCurrent)
if err != nil {
fmt.Println(s, err)
return
}
fmt.Println("offset:", s)
buf := make([]byte, 8)
// the read operation commences at the
// file offset, and the file offset is incremented by the number of
// bytes read. If the file offset is at or past the end of file, no
// bytes are read, and read() returns zero.
n, err = f1.Read(buf[:cap(buf)])
fmt.Println("read: ", n, err)
buf = buf[:n]
fmt.Println("buffer:", len(buf), buf)
if err != nil {
if err != io.EOF {
fmt.Println(n, err)
return
}
}
// The file offset is set to the start-of-file.
s, err = f1.Seek(0, io.SeekStart)
if err != nil {
fmt.Println(s, err)
return
}
fmt.Println("offset:", s)
// the read operation commences at the
// file offset, and the file offset is incremented by the number of
// bytes read. If the file offset is at or past the end of file, no
// bytes are read, and read() returns zero.
n, err = f1.Read(buf[:cap(buf)])
fmt.Println("read: ", n, err)
buf = buf[:n]
fmt.Println("buffer:", len(buf), buf)
if err != nil {
if err != io.EOF {
fmt.Println(n, err)
return
}
}
}
Playground: https://play.golang.org/p/hPUn1ltKP2t
Output:
offset: 0
write: 12 <nil>
offset: 12
read: 0 EOF
buffer: 0 []
offset: 0
read: 8 <nil>
buffer: 8 [115 111 109 101 32 99 111 110]