Read And Write Whole Files
Use os.ReadFile and os.WriteFile for whole-file IO with explicit permissions, and classify read failures with errors.Is instead of panicking.
Code
package main
import (
"errors"
"fmt"
"os"
)
func main() {
path := "score.txt"
// WriteFile:0644 是文件创建权限;覆盖已存在文件
if err := os.WriteFile(path, []byte("score=97\n"), 0o644); err != nil {
fmt.Println("write:", err)
return
}
data, err := os.ReadFile(path)
if err != nil {
fmt.Println("read:", err)
return
}
fmt.Printf("read back: %q", data)
// 读不存在的文件返回 *PathError:用 errors.Is 归类处理
if _, err := os.ReadFile("missing.txt"); err != nil {
fmt.Println("missing:", errors.Is(err, os.ErrNotExist))
}
// 只追加而不是覆盖:O_APPEND 打开后再写
f, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0o644)
if err != nil {
fmt.Println("open:", err)
return
}
if _, err := f.WriteString("score=88\n"); err != nil {
f.Close()
fmt.Println("append:", err)
return
}
f.Close()
again, _ := os.ReadFile(path)
fmt.Printf("after append: %q", again)
os.Remove(path)
}What the code does
Count the function main as the entire surface area of Read And Write Whole Files.
Nothing falls through silently — 5 checkpoints test err != nil on the way through.
Using it
Each run prints the 7 labeled blocks write:, read:, read back:, missing:, open:, append:, after append: in source order.
Key statements
if err != nil {
fmt.Println("read:", err)
return
}
if err != nil {
fmt.Println("open:", err)
return
}
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Read And Write Whole Files print when run?
- Invoke the file as-is — the `write:`, `read:`, `read back:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.