实现说明
ReadFile WriteFile 与 Stat 读小文件的核心是函数 main。
失败处理就是 panic(err):4 个检查点在问题出现的地方中止程序。
使用要点
panic(err)是这里唯一的失败路径:第一个问题就会终止程序。- 跑完文件,输出里会留下标记——
content:、size:、missing:。
常见问题
示例失败时会 panic 吗?
4 处 if err != nil 分支都以 panic(err) 结束——失败的调用之后什么都不会继续。
运行「ReadFile WriteFile 与 Stat 读小文件」会打印什么?
运行文件本身,content:、size:、missing: 这些前缀各对应一段演示逻辑。
核心语句
if err != nil {
panic(err)
}
代码示例
package main
import (
"fmt"
"os"
)
func main() {
// WriteFile: creates the file or truncates an existing one; the 0o644 mode applies only on creation
path := "notes.txt"
if err := os.WriteFile(path, []byte("first line\nsecond line\n"), 0o644); err != nil {
panic(err)
}
// ReadFile slurps the whole content in one call, the most direct route for small files
data, err := os.ReadFile(path)
if err != nil {
panic(err)
}
fmt.Printf("content: %q\n", string(data))
// Stat fetches metadata: size and whether the path is a directory
info, err := os.Stat(path)
if err != nil {
panic(err)
}
fmt.Println("size:", info.Size(), "dir:", info.IsDir())
// Reading a missing file returns an error: os.IsNotExist classifies absent paths
if _, err := os.ReadFile("missing.txt"); err != nil {
fmt.Println("missing:", os.IsNotExist(err))
}
os.Remove(path)
}