atomic

package module
v1.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 10, 2025 License: MIT Imports: 5 Imported by: 0

README

Go API documentation

atomic

Package for atomic file writing (fork of https://github.com/natefinch/atomic with improvements).

Writing to a file can fail in the middle, leading to a partially written file, which probably was truncated when the write began, meaning now data is corrupt or lost.

This package avoids the problem by writing to a temporary file in the same directory first, and then renaming the target file in an atomic way. This is easy on UNIX-like where os.Rename is atomic. On Windows however, where os.Rename is not atomic, bad things can happen. Wrapping the Windows moveFileEx API ensures the move is atomic and either succeeds entirely, or fails and no existing file will be modified.

Usage

import (
	"strings"

	"codeberg.org/sdassow/atomic"
)

func main() {
	r := strings.NewReader("yes\n")
	err := atomic.WriteFile("consistent.txt", r, atomic.FileMode(0440))
	if err != nil {
		// handle error
	}
}

Installation

go get codeberg.org/sdassow/atomic

or with go mod tidy after adding it to imports.

Documentation

Check the Go API Documentation or with go doc -all codeberg.org/sdassow/atomic when added to go.mod.

Documentation

Overview

package atomic provides functions to change files atomically.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultFileMode

func DefaultFileMode(mode os.FileMode) option

DefaultFileMode sets the default file mode instead of using the `ioutil.TempFile()` default of `0600`.

func FileMode

func FileMode(mode os.FileMode) option

FileMode sets the file mode to the desired value and has precedence over all other options.

func KeepFileMode

func KeepFileMode(keep bool) option

KeepFileMode preserves the file mode of an existing file instead of using the default value.

func ReplaceFile

func ReplaceFile(oldpath, newpath string) error

ReplaceFile atomically replaces the destination file or directory with the source. It is guaranteed to either replace the target file entirely, or not change either file.

func WriteFile

func WriteFile(name string, r io.Reader, opts ...option) error

WriteFile atomically writes the contents of r to the specified filepath. If an error occurs, the target file is guaranteed to be either fully written, or not written at all. WriteFile overwrites any file that exists at the location (but only if the write fully succeeds, otherwise the existing file is unmodified). Additional option arguments can be used to change the default configuration for the target file.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL