CodeGym /コース /Go SELF /Why simple file overwrites are dangerous

Why simple file overwrites are dangerous

Go SELF
レベル 42, レッスン 0
使用可能

1. A file is not a variable: why writing is more complicated than it seems

When you first write os.WriteFile("data.txt", data, 0644), it feels nice: "that is it, I have beaten data storage." And that is true... right up until the first time the program crashes in the middle of a write, the disk suddenly runs out of space, or you forget to call Flush(). Then it turns out that a file is not a variable in memory, but an object surrounded by the OS, drivers, buffers, and sudden surprises.

Imagine that you are rewriting an important notebook by hand. If you first erase the old text and then start writing the new one, and at that moment you run out of ink, you do not have "the old notebook" or "the new notebook". You have "half of the new one, half of nothing". A "simple file overwrite" works in much the same way: it often begins by truncating (truncate) the old contents, and after that it is luck.

And this is where the key engineering question appears: what does it mean to "write a file reliably"? Before choosing specific functions, we need to formulate requirements for the result.

2. Invariants of reliable writing: what we want to guarantee

Reliability does not start with os.CreateTemp, not with Rename, and not even with "let us add one more defer." Reliability starts with an honest answer: what result do we consider correct, and which failures must we survive without a catastrophe. Such requirements are conveniently formulated as invariants — properties that must always hold (within our protocol).

Let us formulate a basic set of invariants for "write a new version of data to a file":

Situation What must be true (invariant) Why it matters
The write operation completed successfully The target file contains the new version of the data Otherwise "success" is meaningless
The write operation was interrupted by a failure (crash, kill, power loss, disk full) The target file contains either the old version or the new one, but not a "half-version" The user/program should not read garbage
The operation finished (success/error) There is no "service garbage" (temporary files) left in the working directory So the directory does not turn into a dump
On error The error is understandable: it shows which step failed Otherwise it is impossible to debug

You can think of this as a simple state diagram. What matters is that after a failure we do not end up in the "corrupted file" state.

stateDiagram-v2
    [*] --> Old
    Old: old file version

    Old --> Writing: update started
    Writing --> New: write completed successfully
    Writing --> Old: failure, but the old version remained
    Writing --> New: failure, but the new version became fully visible in time

    Writing --> Corrupted: failure left a half-version (NOT ALLOWED)
    Corrupted --> [*]

The Corrupted state is exactly what is very easy to get with a "simple overwrite". And later in the lecture we will look at why.

3. Where simple overwriting breaks: truncate as the point of catastrophe

The most unpleasant part of "simple overwriting" is that it often starts by destroying the old contents. Even if you later write the new contents perfectly, the very fact that you first made the file empty already violates our second invariant (about failure: "either the old version or the new one").

Look at code like this:

package main

import (
	"fmt"
	"os"
)

func main() {
	err := os.WriteFile("notes.txt", []byte("new version\n"), 0644)
	if err != nil {
		fmt.Println("write failed:", err)
	}
}

It looks harmless. But if notes.txt already existed, we are effectively saying: "overwrite it entirely." Now mentally insert a failure: the program managed to start the update operation, the old file was already truncated, and the new write did not finish. And now you have notes.txt, which may end up empty or contain only part of the data.

A slightly more "manual" version makes the problem even clearer:

package main

import (
	"fmt"
	"os"
)

func main() {
	f, err := os.Create("notes.txt") // creates OR truncates an existing file
	if err != nil {
		fmt.Println("create failed:", err)
		return
	}
	defer f.Close()

	_, _ = f.WriteString("new version\n")
}

Important point: os.Create is not "open a file for writing." It is "create a file, and if it exists — set its length to zero (truncate) and return a descriptor." In other words, the risk point appears right at the beginning, even before any data is written.

Sometimes a developer thinks: "well, if I write quickly, the chance of failure is small." This is exactly the kind of case where a "small chance" turns into a "very large one" in production: because production is the place where everything eventually breaks, simply by principle.

4. The write protocol: Write, Flush, and Close

Partial write: why Write returns (n, err)

Many beginners look at Write and see there a "strange pair" — the number of bytes written and an error. There is a temptation: "I am checking err anyway, why do I need n?" And then a situation happens where err == nil, but fewer bytes were written than you expected. That is not the most common scenario on a normal disk, but the API contract itself says: it can happen, and that means in critical places you need to account for it.

Let us write a small "building block" for reliable writing: a function that checks that exactly the number of bytes we planned was written.

package main

import (
	"fmt"
	"os"
)

func writeAll(f *os.File, data []byte) error {
	n, err := f.Write(data)
	if err != nil {
		return fmt.Errorf("write: %w", err)
	}
	if n != len(data) {
		return fmt.Errorf("write: partial write %d/%d", n, len(data))
	}
	return nil
}

Notice that there is no magic here: we simply treat Write as an honest contract. If the function says "I might not write everything" — then we must check that where "not everything" breaks the meaning of the operation.

And now imagine writing "the naive way": you call Write, ignore n, the program exits "successfully", and then data loading fails because the file turned out to be truncated at a random point. The most unpleasant thing is that the bug looks like "sometimes the file is corrupted", which is an ideal trap for debugging.

Buffering: "I wrote it" != "the data is in the file"

Buffering is like food delivery: you can "place an order" (call WriteString), but that does not yet mean the food is on your table (the data is on disk). bufio.Writer accumulates data in memory and passes it to the file in chunks. That speeds things up, but adds a mandatory step: finalization via Flush(), otherwise the data may remain only in RAM.

The most typical error scenario looks like this: the code "writes", there are no errors, but the file is empty or incomplete.

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	f, err := os.Create("out.txt")
	if err != nil {
		fmt.Println("create:", err)
		return
	}
	defer f.Close()

	w := bufio.NewWriter(f)
	_, _ = w.WriteString("line 1\n")
	_, _ = w.WriteString("line 2\n")

	// Error: forgot Flush()
}

This example is intentionally "nasty": it shows that "no errors" still does not mean "the result is correct." If you want data to definitely pass through the buffer into the file, Flush() must become part of the protocol:

package main

import (
	"bufio"
	"fmt"
	"os"
)

func main() {
	f, err := os.Create("out.txt")
	if err != nil {
		fmt.Println("create:", err)
		return
	}
	defer f.Close()

	w := bufio.NewWriter(f)
	_, _ = w.WriteString("ok\n")

	if err := w.Flush(); err != nil {
		fmt.Println("flush:", err)
	}
}

And one more important point: Flush() can also return an error. This is not a "formality," but a real point where a write problem may surface (for example, if the disk is full). Therefore "reliable writing" always means "check errors at every protocol step," not only on the first line.

Close() is not a formality: the error may come at close

It is very tempting to think that Close() is like "putting a stool back in place": it always works and cannot be a source of problems. But in write scenarios Close() is sometimes the moment when the system tries to "finish the remaining work": flush internal buffers, complete the I/O operation, and commit state. So in serious places Close() is part of the protocol, and its error must be taken into account.

In Go people often write this:

f, err := os.Create(path)
if err != nil {
	return err
}
defer f.Close()

For reading, this is usually fine: if we read and Close() suddenly returns an error, that is often not critical for the result (though it also depends on the situation). But for writing, people sometimes do it differently: they close the file explicitly and check the error. It looks a bit longer, but more honest.

package main

import (
	"fmt"
	"os"
)

func main() {
	f, err := os.Create("data.txt")
	if err != nil {
		fmt.Println("create:", err)
		return
	}

	if _, err := f.WriteString("payload\n"); err != nil {
		_ = f.Close()
		fmt.Println("write:", err)
		return
	}

	if err := f.Close(); err != nil {
		fmt.Println("close:", err)
		return
	}
}

Yes, this is not the prettiest code in the world. But it highlights the lecture's point: reliability is a protocol, not "one call." A protocol has steps, and each step can fail.

Here it is useful to remember the general philosophy of Go: errors must be checked explicitly, because they are ordinary values, and that is the language's strength.

5. The storage contract in the application: Save is a commitment

When we build a training app (even a very simple local task manager), there is usually a function like "save the task list to a file." And at early stages you want to do this as simply as possible: take the data, call os.WriteFile, done. But as soon as the file becomes the "source of truth" (that is, without it the user loses data), such simplicity starts to cost too much.

Let us fix a minimal API for the storage layer: functions Load and Save, which do not print anything, but return errors. This is an important style: storage should not deal with UX; it should deal with correctness.

package storage

import (
	"fmt"
	"os"
)

func SaveText(path string, data string) error {
	if err := os.WriteFile(path, []byte(data), 0644); err != nil {
		return fmt.Errorf("save file %s: %w", path, err)
	}
	return nil
}

The code is intentionally "naive": it shows the starting point. From the point of view of convenience — perfect. From the point of view of our invariants — dangerous, because overwrite does not guarantee "either old or new."

And now we can formulate requirements for the next version of SaveText (without implementing it in detail here). We want the file not to turn into a half-version after failure. We want to have a "commit" point after which the new version is considered published. We want garbage not to remain nearby. And we want the error to say "which step" failed.

Notice that we are not discussing a specific mechanism yet. We are doing something more important: turning "which function to call" into "which contract we must fulfill." That is adult development: first agree on correctness, then choose a tool.

6. Typical mistakes when simply overwriting a file

Mistake #1: assuming that os.WriteFile is always safe because "one function means atomic."
os.WriteFile does have a convenient interface, but convenience is not the same as reliability. In reality, overwriting often means the old file will be replaced/truncated, and on failure you may be left with a "half-version." If the file matters, first formulate the invariants and check whether the chosen approach satisfies them.

Mistake #2: forgetting that writing is several steps, and the error may arrive not where you expect it.
Beginners check the error on Write, and treat Flush() and Close() as "always ok." Then a mysterious bug appears: "sometimes the file is empty" or "sometimes the file is truncated." The right habit is to treat finalization as part of the protocol: if there is a buffer, Flush() is needed; if there is a file, Close() can be a significant step.

Mistake #3: ignoring n from Write because "well, the error is separate."
The Write contract in Go honestly says: a partial write is possible. If you ignore n, you deprive yourself of the ability to detect data corruption immediately. Sometimes it is better to return a meaningful "partial write 10/100" error than later to figure out why the file parser complains at a random place.

Mistake #4: returning an error "as is", without operation context.
An error like "permission denied" without saying what you were doing and with which file turns debugging into guessing. Wrap errors with fmt.Errorf("save file %s: %w", path, err). In Go this is a basic practice: an error must carry context, otherwise it is almost useless.

Mistake #5: mixing "storage" and "user output" in one place.
If your Save prints to stdout/stderr, it is hard to test and hard to reuse. Let Save return error, and let the external layer (CLI/server) decide whether to print/log/crash. Then the invariants are easier to check, and behavior becomes predictable.

1
タスク
Go SELF, レベル 42, レッスン 0
ロック未解除
ゼロのページ
ゼロのページ
1
タスク
Go SELF, レベル 42, レッスン 0
ロック未解除
バッファプロトコル
バッファプロトコル
1
タスク
Go SELF, レベル 42, レッスン 0
ロック未解除
信頼性の高い保存
信頼性の高い保存
1
タスク
Go SELF, レベル 42, レッスン 0
ロック未解除
途中で中断された更新
途中で中断された更新
コメント
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION