Skip to content

Instantly share code, notes, and snippets.

@hnakamur
Created May 3, 2023 23:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hnakamur/947c13eeb35452771858cc9372b902af to your computer and use it in GitHub Desktop.
Save hnakamur/947c13eeb35452771858cc9372b902af to your computer and use it in GitHub Desktop.
verify Go os.File.Read returns 0, io.EOF at end of file.
package main
import (
"io"
"log"
"os"
)
func main() {
if err := run(); err != nil {
log.Fatal(err)
}
}
func run() error {
const filename = "hello.txt"
if err := os.WriteFile(filename, []byte("hello"), os.FileMode(0o600)); err != nil {
return err
}
defer os.Remove(filename)
file, err := os.Open(filename)
if err != nil {
return err
}
defer file.Close()
var buf [4]byte
for {
n, err := file.Read(buf[:])
log.Printf("n=%d, err=%v", n, err)
if err == io.EOF {
break
}
if err != nil {
return err
}
}
return nil
}
@hnakamur
Copy link
Author

hnakamur commented May 3, 2023

https://pkg.go.dev/os@go1.20.4#File.Read

$ go version
go version go1.20.4 linux/amd64
$ go run .
2023/05/04 08:05:42 n=4, err=<nil>
2023/05/04 08:05:42 n=1, err=<nil>
2023/05/04 08:05:42 n=0, err=EOF

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment