package main
import (
"bufio"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"reflect"
"runtime"
"sort"
"strconv"
"strings"
)
type Case struct {
Name string `json:"name"`
Summary string `json:"summary"`
Expected any `json:"expected"`
Actual any `json:"actual"`
Passed bool `json:"passed"`
}
type Report struct {
Version string `json:"version"`
Cases []Case `json:"cases"`
}
func makeCase(name, summary string, expected, actual any) Case {
return Case{
Name: name,
Summary: summary,
Expected: expected,
Actual: actual,
Passed: reflect.DeepEqual(expected, actual),
}
}
func copyFile(src, dst string) (int64, error) {
sf, err := os.Open(src)
if err != nil {
return 0, err
}
defer sf.Close()
df, err := os.Create(dst)
if err != nil {
return 0, err
}
defer df.Close()
return io.Copy(df, sf)
}
func main() {
tmpDir, err := os.MkdirTemp("", "golab-file-*")
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
defer os.RemoveAll(tmpDir)
var cases []Case
// Case 1: os.Create, os.Open (RO), os.OpenFile (O_EXCL, O_APPEND)
createPath := filepath.Join(tmpDir, "created.txt")
f, err := os.Create(createPath)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
_, _ = f.WriteString("first-content\n")
_ = f.Close()
// Truncate with os.Create
f2, _ := os.Create(createPath)
_, _ = f2.WriteString("truncated-content\n")
_ = f2.Close()
// Read-only open fails on write
roFile, err := os.Open(createPath)
roOpenOk := err == nil
_, roWriteErr := roFile.WriteString("fail")
_ = roFile.Close()
// O_CREATE | O_EXCL fails when file already exists
_, exclErr := os.OpenFile(createPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0644)
// Append mode preserves prior lines
logPath := filepath.Join(tmpDir, "app.log")
for _, entry := range []string{"line-1\n", "line-2\n"} {
lf, _ := os.OpenFile(logPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
_, _ = lf.WriteString(entry)
_ = lf.Close()
}
logBytes, _ := os.ReadFile(logPath)
createdBytes, _ := os.ReadFile(createPath)
actual1 := map[string]any{
"create_trunc_content": string(createdBytes),
"ro_open_ok": roOpenOk,
"ro_write_failed": roWriteErr != nil,
"excl_exists_err": errors.Is(exclErr, os.ErrExist),
"append_content": string(logBytes),
}
expected1 := map[string]any{
"create_trunc_content": "truncated-content\n",
"ro_open_ok": true,
"ro_write_failed": true,
"excl_exists_err": true,
"append_content": "line-1\nline-2\n",
}
cases = append(cases, makeCase(
"file_create_open_and_flags",
"核对 os.Create 截断、os.Open 只读限制、O_CREATE|O_EXCL 冲突检查及 O_APPEND 追加写入",
expected1, actual1,
))
// Case 2: Three reading modes (os.ReadFile, bufio.Scanner + custom Buffer, io.ReadAll)
readPath := filepath.Join(tmpDir, "multi.txt")
longLine := strings.Repeat("x", 70000)
_ = os.WriteFile(readPath, []byte("alpha\nbeta\n"+longLine+"\n"), 0644)
allViaReadFile, _ := os.ReadFile(readPath)
sf, _ := os.Open(readPath)
scanner := bufio.NewScanner(sf)
scanner.Buffer(make([]byte, 0, 1024), 128*1024)
var lineLens []int
var firstTwo []string
for scanner.Scan() {
txt := scanner.Text()
lineLens = append(lineLens, len(txt))
if len(firstTwo) < 2 {
firstTwo = append(firstTwo, txt)
}
}
scanErr := scanner.Err()
_ = sf.Close()
rf, _ := os.Open(readPath)
allViaIO, ioErr := io.ReadAll(rf)
_ = rf.Close()
actual2 := map[string]any{
"readfile_len": len(allViaReadFile),
"scanner_err_nil": scanErr == nil,
"scanner_first2": firstTwo,
"scanner_line_len": lineLens,
"io_readall_match": ioErr == nil && string(allViaIO) == string(allViaReadFile),
}
expected2 := map[string]any{
"readfile_len": 70012,
"scanner_err_nil": true,
"scanner_first2": []string{"alpha", "beta"},
"scanner_line_len": []int{5, 4, 70000},
"io_readall_match": true,
}
cases = append(cases, makeCase(
"file_read_modes",
"核对 os.ReadFile、bufio.Scanner(含自定义 Buffer 处理 70KB 超长行)与 io.ReadAll 读取",
expected2, actual2,
))
// Case 3: Three writing modes (os.WriteFile, File methods, bufio.Writer + Flush)
w1Path := filepath.Join(tmpDir, "w1.txt")
_ = os.WriteFile(w1Path, []byte("Hello, Go!\nLine 2\n"), 0644)
w1Data, _ := os.ReadFile(w1Path)
w2Path := filepath.Join(tmpDir, "w2.txt")
wf, _ := os.Create(w2Path)
_, _ = wf.WriteString("str\n")
_, _ = wf.Write([]byte("bytes\n"))
_, _ = fmt.Fprintf(wf, "%d+%d=%d\n", 3, 4, 7)
_ = wf.Close()
w2Data, _ := os.ReadFile(w2Path)
w3Path := filepath.Join(tmpDir, "w3.txt")
bf, _ := os.Create(w3Path)
bw := bufio.NewWriter(bf)
for i := 0; i < 200; i++ {
_, _ = bw.WriteString("row-" + strconv.Itoa(i) + "\n")
}
flushErr := bw.Flush()
_ = bf.Close()
w3Data, _ := os.ReadFile(w3Path)
w3Lines := strings.Split(strings.TrimSpace(string(w3Data)), "\n")
actual3 := map[string]any{
"writefile_text": string(w1Data),
"file_methods": string(w2Data),
"bufio_flush_ok": flushErr == nil,
"bufio_line_cnt": len(w3Lines),
"bufio_last_line": w3Lines[len(w3Lines)-1],
}
expected3 := map[string]any{
"writefile_text": "Hello, Go!\nLine 2\n",
"file_methods": "str\nbytes\n3+4=7\n",
"bufio_flush_ok": true,
"bufio_line_cnt": 200,
"bufio_last_line": "row-199",
}
cases = append(cases, makeCase(
"file_write_modes",
"核对 os.WriteFile、File.WriteString/Write/fmt.Fprintf 及 bufio.Writer+Flush 缓冲写入",
expected3, actual3,
))
// Case 4: os.Stat, existence check, os.Rename, os.Remove
oldPath := filepath.Join(tmpDir, "old.txt")
newPath := filepath.Join(tmpDir, "new.txt")
_, missingErr := os.Stat(oldPath)
_ = os.WriteFile(oldPath, []byte("payload123"), 0644)
info, statErr := os.Stat(oldPath)
renameErr := os.Rename(oldPath, newPath)
_, oldAfterRename := os.Stat(oldPath)
_, newBeforeRemove := os.Stat(newPath)
removeErr := os.Remove(newPath)
_, newAfterRemove := os.Stat(newPath)
actual4 := map[string]any{
"missing_before": errors.Is(missingErr, os.ErrNotExist) && os.IsNotExist(missingErr),
"stat_ok": statErr == nil,
"stat_name": info.Name(),
"stat_size": int(info.Size()),
"stat_is_dir": info.IsDir(),
"rename_ok": renameErr == nil,
"old_gone_after_mv": errors.Is(oldAfterRename, os.ErrNotExist),
"new_exists_after_mv": newBeforeRemove == nil,
"remove_ok": removeErr == nil,
"new_gone_after_rm": errors.Is(newAfterRemove, os.ErrNotExist),
}
expected4 := map[string]any{
"missing_before": true,
"stat_ok": true,
"stat_name": "old.txt",
"stat_size": 10,
"stat_is_dir": false,
"rename_ok": true,
"old_gone_after_mv": true,
"new_exists_after_mv": true,
"remove_ok": true,
"new_gone_after_rm": true,
}
cases = append(cases, makeCase(
"file_stat_exists_rename_remove",
"核对 os.Stat 文件元数据、os.ErrNotExist/os.IsNotExist 存在判定及 os.Rename/os.Remove",
expected4, actual4,
))
// Case 5: Directory operations, io.Copy, os.CreateTemp, filepath.Walk, filepath.Join
subRoot := filepath.Join(tmpDir, "tree")
_ = os.Mkdir(subRoot, 0755)
_ = os.MkdirAll(filepath.Join(subRoot, "a", "b"), 0755)
srcCopy := filepath.Join(subRoot, "src.txt")
dstCopy := filepath.Join(subRoot, "a", "b", "dst.txt")
_ = os.WriteFile(srcCopy, []byte("copy-data-ok"), 0644)
copiedN, copyErr := copyFile(srcCopy, dstCopy)
dstData, _ := os.ReadFile(dstCopy)
var walked []string
_ = filepath.Walk(subRoot, func(p string, fi os.FileInfo, e error) error {
if e != nil {
return e
}
rel, _ := filepath.Rel(subRoot, p)
if rel != "." {
walked = append(walked, filepath.ToSlash(rel))
}
return nil
})
sort.Strings(walked)
tf, tfErr := os.CreateTemp(tmpDir, "app-*.txt")
tfBase := filepath.Base(tf.Name())
_ = tf.Close()
_ = os.Remove(tf.Name())
entries, _ := os.ReadDir(subRoot)
var rootNames []string
for _, en := range entries {
rootNames = append(rootNames, en.Name())
}
sort.Strings(rootNames)
actual5 := map[string]any{
"copy_ok": copyErr == nil,
"copy_bytes": int(copiedN),
"copy_content": string(dstData),
"read_dir": rootNames,
"walked": walked,
"temp_matched": tfErr == nil && strings.HasPrefix(tfBase, "app-") && strings.HasSuffix(tfBase, ".txt"),
"filepath_join": filepath.Join("dir", "sub", "file.txt"),
}
expected5 := map[string]any{
"copy_ok": true,
"copy_bytes": 12,
"copy_content": "copy-data-ok",
"read_dir": []string{"a", "src.txt"},
"walked": []string{"a", "a/b", "a/b/dst.txt", "src.txt"},
"temp_matched": true,
"filepath_join": "dir/sub/file.txt",
}
cases = append(cases, makeCase(
"dir_copy_temp_walk_join",
"核对目录创建遍历、io.Copy 复制、os.CreateTemp 临时文件、filepath.Walk 与 filepath.Join",
expected5, actual5,
))
report := Report{
Version: fmt.Sprintf("%s %s/%s", runtime.Version(), runtime.GOOS, runtime.GOARCH),
Cases: cases,
}
enc := json.NewEncoder(os.Stdout)
enc.SetEscapeHTML(false)
enc.SetIndent("", " ")
if err := enc.Encode(report); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
本例需在 本地离线 Docker 容器(golang:1.22-alpine,go1.22.12 linux/amd64,--network none)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:本地离线 Docker 容器(golang:1.22-alpine,go1.22.12 linux/amd64,--network none)。
入口文件:projects/go-file-handle-lab/explore_file-handle.go
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore_file-handle.go,或下载右侧课程工程包。 - 确认本地已准备 本地离线 Docker 容器(golang:1.22-alpine,go1.22.12 linux/amd64,--network none)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联33章) · 含当前章节或实例 · mbskycom202612a1159.zip
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1167.zip