CodeGym /コース /Go SELF /Go でのファイル操作: Open/Create/OpenFile

Go でのファイル操作: Open/Create/OpenFile

Go SELF
レベル 39, レッスン 1
使用可能

1. File as a resource: open it — close it

When we first start programming, a file feels a bit like a “folder of letters” that we can access at any moment. But for the operating system, a file is a resource that you open, obtain a “handle” (a descriptor), and then are required to close. If you do not close files, the program may seem to work at first, but then it suddenly starts behaving strangely: it cannot open new files, it does not write data all the way through, or it throws weird errors.

In Go, an open file is represented by the type *os.File. This value does not store the whole file in memory at once (that is important!); it stores access to the file through the OS. So the main rule of today’s lecture is: open the file — close the file, and the best way to do that is immediately with defer.

To make this easier to picture, it helps to keep a mini life-cycle diagram in mind:

flowchart TD
    A[Collected the file path] --> B[Opened/created the file -> got *os.File]
    B --> C["Immediately set defer Close()"]
    C --> D["Read or write (Read/Write/WriteString)"]
    D --> E[Function ends -> defer closes the file]

2. defer f.Close(): place it after checking err

defer in Go is not “magic,” but a very practical mechanism: it guarantees that the needed call will happen when the function exits, even if the exit happens through return in the middle. In the official file-copy example, defer is placed right after a successful os.Open/os.Create, so that the resource is not forgotten on any execution path.

The key point for beginners: do not place defer before checking the error. First you check err, and only if err == nil do you have a valid *os.File that can be closed.

The correct pattern looks like this:

package main

import (
	"fmt"
	"os"
)

func main() {
	f, err := os.Open("items.txt")
	if err != nil {
		fmt.Println("open:", err)
		return
	}
	defer f.Close() // ok: f is definitely not nil and the file is really open

	fmt.Println("file opened") // file opened
}

If you place defer f.Close() before if err != nil, then on error f will be nil, and you will run into a different problem instead, most likely a panic when trying to close a nil pointer or a secondary behavior error. In other words, you tried to fix one thing and broke another — the classic programmer diet of “eat bugs, wash them down with bugs.”

3. File opening modes: Open, Create, OpenFile

os.Open: read an existing file

os.Open(name) is the simplest way to open a file for reading. It does not create a file, overwrite it, or append to it — it simply opens an existing file. This is a great mode when you want to load data, for example a list of tasks in a small educational app.

Low-level reading is done through the method Read(p []byte) (n int, err error). It tries to read data into your buffer p and returns how many bytes were actually read. The error io.EOF in this context is not a “catastrophe,” but a normal signal saying “we reached the end of the file.”

Mini example: read the first 8 bytes (just to demonstrate the mechanics):

package main

import (
	"fmt"
	"io"
	"os"
)

func main() {
	f, err := os.Open("items.txt")
	if err != nil {
		fmt.Println("open:", err)
		return
	}
	defer f.Close()

	buf := make([]byte, 8)
	n, err := f.Read(buf)
	if err != nil && err != io.EOF {
		fmt.Println("read:", err)
		return
	}

	fmt.Printf("read %d bytes: %q\n", n, buf[:n]) // read 0 bytes: ""
}

Pay attention to the check: err != nil && err != io.EOF. We are explicitly saying: “any error is bad, but EOF is a normal completion.” This is a simple habit that saves a lot of nerves once you start reading files in chunks.

Do not try to interpret buf as a whole: use buf[:n]. Otherwise you will print extra zero bytes and think the file is “full of some \x00s.”

os.Create: write with truncation

If os.Open means “read only,” then os.Create(name) means “write from scratch.” It creates the file if it does not exist, and if the file does exist, it truncates its contents (truncate). This behavior is useful when you want to save the file again from scratch, but dangerous if you were accidentally expecting “append.”

So Create is like a “new version of the document” button that does not ask, “Are you sure?” That is why we use it deliberately.

Example: overwrite the file "items.txt" with one line.

package main

import (
	"fmt"
	"os"
)

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

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

The method WriteString is convenient when you write text. It returns (n int, err error) — the number of bytes written. In educational examples we often ignore n, but in “real” code partial writes (rare, but possible) can matter.

os.OpenFile: a universal way and flags

When you see os.Open, os.Create, and then os.OpenFile, it can feel like: “why not just leave one option?” In fact, OpenFile is the universal mechanism. And Open and Create are simply convenient “preconfigured” variants for the most common cases.

The signature is:

os.OpenFile(name string, flag int, perm os.FileMode) (*os.File, error)

Here flag is a bit mask (we are not diving into bits today; it is enough to think of it as something you can combine with |), and perm is the access permission applied when the file is created.

The minimal set of flags we need today:

  • os.O_WRONLY — open for writing only,
  • os.O_CREATE — create the file if it does not exist,
  • os.O_EXCL — “create only if it does not exist” (usually together with O_CREATE),
  • os.O_APPEND — always write at the end of the file.

To avoid keeping everything in your head as a mess, here is a small cheat sheet table:

Task How to open
Read an existing file
os.Open(name)
Overwrite the file from scratch
os.Create(name)
Append to the end (log, list of lines)
os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
Create “strictly once” (do not overwrite)
os.OpenFile(name, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644)

O_APPEND: append to the end

When you store data as a list of lines (for example, one “task” per line), the natural scenario is to add a new line at the end. That is exactly what O_APPEND does.

Imagine a small educational app, a “to-do list”: we want to add a new task to the file without overwriting everything. Mini function appendLine:

package main

import (
	"fmt"
	"os"
)

func appendLine(filename string, line string) error {
	f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
	if err != nil {
		return fmt.Errorf("open for append %q: %w", filename, err)
	}
	defer f.Close()

	if _, err := f.WriteString(line + "\n"); err != nil {
		return fmt.Errorf("append line to %q: %w", filename, err)
	}
	return nil
}

func main() {
	if err := appendLine("items.txt", "walk the dog"); err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println("ok") // ok
}

Here we get several useful habits “in one package”: we use OpenFile because we need append mode; we place defer f.Close() immediately after a successful open; and we add context to errors with "%w", so the original cause is not lost and can be recognized higher up the stack.

O_CREATE | O_EXCL: create only if the file does not exist

Sometimes you need the behavior “create the file, but only if it does not already exist.” This is useful for scenarios like “initial setup,” “lock file,” or “create a config template without overwriting the user’s one.”

For this, there is the combination O_CREATE|O_EXCL. The meaning: O_CREATE allows creation, while O_EXCL requires that the file does not exist. If the file already exists, you get an error.

Example: create the file "items.txt" only once and write a header:

package main

import (
	"fmt"
	"os"
)

func createOnce(filename string) error {
	f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644)
	if err != nil {
		return fmt.Errorf("create once %q: %w", filename, err)
	}
	defer f.Close()

	if _, err := f.WriteString("# todo items\n"); err != nil {
		return fmt.Errorf("write header: %w", err)
	}
	return nil
}

func main() {
	if err := createOnce("items.txt"); err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println("created") // created
}

Notice that for now we do not classify the “file already exists” error as a separate branch (that will be a separate topic about error classes). In this lecture, it is important to understand the mechanics and the very idea of “strict creation.”

4. Typical I/O errors and normal io.EOF

Working with files is one of those places where errors are not just possible, but inevitable. The file may not exist. The process may not have permissions. The path may point to a directory rather than a file. The file may be locked by another process (in some OS scenarios). And the worst part: the error may happen not on Open, but on Write (for example, the disk runs out of space).

It is psychologically useful to accept the fact: “I/O errors are not shameful, they are reality.” The programmer’s job is not to “avoid them forever,” but to check err carefully after operations, add clear context, remember to close resources, and not confuse normal signals like io.EOF with a real failure.

By the way, the good news is that errors in Go are values; you can wrap them, pass them upward, and analyze them. In the standard library, errors often contain structure and additional fields, not just text — that is one of the reasons why Go likes the “errors are values” approach so much.

The practical takeaway for this level: never write code that ignores err for file operations. Even if it “seems to work.”

5. Example: todo in a file

To avoid leaving today’s lecture as a pile of unrelated calls, let us build a small (and honest) story. Suppose we have the simplest possible “add a task” command. We are not making a full CLI parser, complex formats, JSON, or anything like that yet. It is enough to show that a file can be used as a very simple journal.

We will do two steps: first “initialize” the file if it does not exist using createOnce, and then append tasks using appendLine.

Here is a compact version (yes, this is still one file, "main.go": today the file mechanics matter more than package architecture):

package main

import (
	"fmt"
	"os"
)

func createOnce(filename string) error {
	f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0644)
	if err != nil {
		return fmt.Errorf("create once %q: %w", filename, err)
	}
	defer f.Close()

	_, err = f.WriteString("# todo items\n")
	if err != nil {
		return fmt.Errorf("write header: %w", err)
	}
	return nil
}

func appendLine(filename string, line string) error {
	f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
	if err != nil {
		return fmt.Errorf("open for append %q: %w", filename, err)
	}
	defer f.Close()

	_, err = f.WriteString(line + "\n")
	if err != nil {
		return fmt.Errorf("append: %w", err)
	}
	return nil
}

func main() {
	_ = createOnce("items.txt") // if the file already exists, this will be an error; for now we ignore it

	if err := appendLine("items.txt", "learn os.OpenFile flags"); err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println("saved") // saved
}

What matters here “semantically”: we do not use os.Create, because it would erase the file every time, and we want a “journal”; we use OpenFile with O_APPEND, because that fits the model “each task is a new line” perfectly; and we close the file honestly via defer, so that even if writing fails, the resource is not left open. Yes, we temporarily ignore the createOnce error (this is an educational trick so the file is created on the first run). In a real application, you would distinguish error causes and behave more carefully, but for now our goal is to understand opening modes.

6. Typical mistakes when working with files and defer Close

Mistake #1: forgot to close the file (or closed it “somewhere later”).
The most common beginner problem is to open a file and “close it somewhere later.” That “later” is easy to lose, especially when the code has many return paths for errors. It is much more reliable to place defer f.Close() immediately after checking err, as soon as the file is successfully opened. This style is not just nice-looking — it really prevents resource leaks.

Mistake #2: placed defer f.Close() before checking err.
This looks like “well, I want to always close it,” but if Open/Create returned an error, the variable f is not a valid file. Then you risk a panic or a secondary error that hides the real cause. The correct order is: first if err != nil, then defer.

Mistake #3: used os.Create, expecting to “append to the end.”
Create does not “open for writing,” it actually creates the file from scratch and truncates the existing one. So for logs, journals, and lists of lines you need os.OpenFile with O_APPEND. If you do not remember this difference, you can accidentally erase a data file one day… and very quickly learn the word “truncate” on an emotional level.

Mistake #4: do not check err for WriteString/Write.
Sometimes it seems: “well, writing is simple, what could go wrong?” And then the disk suddenly fills up, a network disk disconnects, or the file turns out to be read-only. Write errors are just as real as open errors, so if _, err := f.WriteString(...); err != nil { ... } is not bureaucracy, but insurance.

Mistake #5: treat io.EOF as a “fatal error.”
When reading in chunks, EOF means “that is all, there is no more data.” This is not a “broken” situation, but a normal completion signal. So the typical check looks like: “if err is not nil and not EOF — then there is a problem.” Otherwise you will start “fixing” normal behavior and get confused by the reading logic.

1
タスク
Go SELF, レベル 39, レッスン 1
ロック未解除
ウェルカムファイル
ウェルカムファイル
1
タスク
Go SELF, レベル 39, レッスン 1
ロック未解除
チャンク単位での読み取り
チャンク単位での読み取り
1
タスク
Go SELF, レベル 39, レッスン 1
ロック未解除
ログへの追記
ログへの追記
1
タスク
Go SELF, レベル 39, レッスン 1
ロック未解除
一回限りの初期化
一回限りの初期化
コメント
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION