Write Files Atomically With Temp Rename

Stage writes in a same-directory temp file then os.Rename it over the target, so readers see the old or the new content and never a partial write.

GoData Integrity

Code

gosnippet
58 lines
package main

import (
	"fmt"
	"os"
	"path/filepath"
)

func main() {
	dir, err := os.MkdirTemp("", "atomic-demo")
	if err != nil {
		fmt.Println("tmpdir:", err)
		return
	}
	defer os.RemoveAll(dir)

	target := filepath.Join(dir, "release.txt")

	if err := writeFileAtomic(target, []byte("build 42\nchecksum ok\n")); err != nil {
		fmt.Println("write:", err)
		return
	}
	content, err := os.ReadFile(target)
	if err != nil {
		fmt.Println("read:", err)
		return
	}
	fmt.Printf("target now:\n%s", content)

	// 再次原子替换:读方要么看到旧内容,要么看到新内容
	if err := writeFileAtomic(target, []byte("build 43\nchecksum ok\n")); err != nil {
		fmt.Println("write:", err)
		return
	}
	info, _ := os.Stat(target)
	fmt.Println("size after replace:", info.Size())
}

// writeFileAtomic 先写同目录临时文件,再用 rename 一步替换目标:
// 读方永远不会读到写到一半的文件;失败时由 defer 清理临时文件
func writeFileAtomic(path string, data []byte) error {
	tmp, err := os.CreateTemp(filepath.Dir(path), filepath.Base(path)+".tmp-*")
	if err != nil {
		return err
	}
	tmpPath := tmp.Name()
	defer os.Remove(tmpPath) // rename 成功后 Remove 是空操作

	if _, err := tmp.Write(data); err != nil {
		tmp.Close()
		return err
	}
	// rename 前必须先关闭句柄
	if err := tmp.Close(); err != nil {
		return err
	}
	return os.Rename(tmpPath, path)
}

The structure at work

Write Files Atomically With Temp Rename comes down to the functions main and writeFileAtomic.

The Go idiom runs throughout — 7 if err != nil checks, each handling the failure on the spot. A defer statement pins the cleanup to the function boundary rather than scattering it through the body.

What to watch for

  • Nothing arrives from a registry; the language ships every API used.
  • Failure is a return value (error), which keeps control flow explicit at every call site.

Using it

The main signature reads func main()

The demo output is labeled (tmpdir:, write:, read:), so the output doubles as a step-by-step trace of what the file did.

main is the driver: it invokes writeFileAtomic before returning.

Key statements

if err != nil {
fmt.Println("tmpdir:", err)
return
}
if err != nil {
fmt.Println("read:", err)
return
}
if err != nil {
return err
}

Interactive Tools for This Topic

FAQ

How should callers handle failures?
No exceptions — `error` returns checked at 7 sites, and callers branch on `err` first.
What does Write Files Atomically With Temp Rename print when run?
Execute the whole file; each printed line is prefixed with a label like `tmpdir:`, `write:`, `read:`.