CodeGym /행동 /Go SELF /os.ReadFile/WriteFile: when you can read and write

os.ReadFile/WriteFile: when you can read and write

Go SELF
레벨 39, 레슨 2
사용 가능

1. Introduction

When you first see os.ReadFile, suspicion arises: “What is this, for lazy people? And what about ‘proper’ reading through Open and Read?” In reality, ReadFile/WriteFile are not “cheat codes” but an honest shortcut for a typical case: the file is small, we need to get it in full, process it in memory, and maybe write it back.

It is like cooking: sometimes you need to “simmer the broth for 8 hours”, and sometimes you need a sandwich. A sandwich is not shameful if you actually wanted to eat, not win a “Michelin” for home cooking.

os.ReadFile: contract, result type, and why it returns []byte

It is important to set expectations right away: os.ReadFile(path) reads the entire file and returns []byte and error. In other words, you get a “raw” byte slice. That makes sense: a file may be text, but it may also be an image, a zip archive, or something that does not look like text at all. Go will not pretend that every file is a string.

At the level of thinking, it looks like this:

path → ReadFile → bytes (in memory) → your processing

Minimal reading example:

package main

import (
	"fmt"
	"os"
)

func main() {
	b, err := os.ReadFile("data/todo/items.txt")
	if err != nil {
		fmt.Println("readfile:", err)
		return
	}

	fmt.Printf("bytes=%d\n", len(b)) // for example: bytes=42
}

Here it is important that we are not pretending this is text yet. We have simply read the bytes and checked the size.

2. Converting bytes to text and back

As soon as you understand that the file is really textual (for example, our task list is a plain .txt file), you make an explicit conversion: string(b). This is not “magic” but a clear statement: “yes, I consider these bytes to be text.”

package main

import (
	"fmt"
	"os"
)

func main() {
	b, err := os.ReadFile("data/todo/items.txt")
	if err != nil {
		fmt.Println("readfile:", err)
		return
	}

	text := string(b)
	fmt.Printf("text=%q\n", text) // text="buy milk\nread go\n"
}

Pay attention to %q: it shows the string in quotes and makes \n visible. For diagnostics, this is more convenient than just Println.

The reverse operation for writing is []byte(text):

data := []byte("hello\n")

Yes, it looks like “changing clothes” back and forth, but this is exactly how you keep control over what you consider text and what is just a byte sequence.

4. os.WriteFile: what it does and why it matters

With os.WriteFile(path, data, perm) there is one thing that beginners regularly miss: WriteFile writes the whole file and, if the file already exists, usually overwrites its contents. In other words, this is a “burn the old and build the new” mode (figuratively; the disk does not mind, but your data may).

Minimal example:

package main

import (
	"fmt"
	"os"
)

func main() {
	err := os.WriteFile("data/todo/items.txt", []byte("one\ntwo\n"), 0644)
	if err != nil {
		fmt.Println("writefile:", err)
		return
	}
	fmt.Println("ok") // ok
}

The third parameter is permissions (perm). For now, it is enough to remember: this is important when creating a file. If the file already exists, the behavior of permissions depends on the OS and details; usually perm is not understood as “set the permissions exactly as I said” for an existing file. We will not go into permission details now — it is more important to understand that perm should not be thrown away “just because it is unclear”.

Comparison: Open/Create versus ReadFile/WriteFile

When different ways of working with files get mixed up in your head, a simple comparison table helps. There is no “better/worse” here, only “fits the task/does not fit”.

Task Approach Why
Read a small file in full (config, list of lines)
os.ReadFile
Simplicity: one call and all data immediately
Write a small file in full (save state again)
os.WriteFile
Simplicity and predictability: wrote it “as is”
Read a large file in chunks
os.Open + Read
ReadFile will consume memory proportional to file size
Append to the end (log)
os.OpenFile(...|os.O_APPEND...)
WriteFile is not for “append”, it is for “overwrite”
Keep a file open for a long time
*os.File
ReadFile/WriteFile open/close on their own, “in one go”

Separately, I will emphasize: os.Open returns *os.File and error, and it is normal that almost everything in Go works like this.

5. Where ReadFile/WriteFile are truly good

It is very tempting to have a “rule for every case”, but life is trickier: you will write both small utilities and services and data importers. So it is useful to keep a practical criterion in mind: if the file is small and, by meaning, you work with all of its contents at once — ReadFile/WriteFile are perfect.

For example, a small text file with a task list that our educational project stores on disk is exactly the “native” situation. We read the whole file, parse the lines, add one task, and write the file back in full. Yes, it is “overwrite”, but if the file is a couple of kilobytes, it is fast and simple.

Here it is important not to confuse convenience with irresponsibility. Convenience is when the data size is known and manageable. Irresponsibility is when you do ReadFile on an 8 GB file “just in case”.

6. Where ReadFile/WriteFile start acting up

ReadFile/WriteFile have limitations, and they are not “rare theoretical” ones, but very real.

The first limitation is memory. ReadFile reads the whole file into []byte, which means memory is needed roughly equal to the file size (plus overhead). If you ever read a huge file in full, you will get either slowdowns or an out-of-memory failure. And yes, this is the moment when the computer starts behaving like a person without caffeine: technically alive, but very unhappy.

The second limitation is write semantics. WriteFile is about “write all at once”, not “append a small piece to the end”. If you need a log or a format where you “add new entries line by line”, WriteFile quickly turns into a strange ritual: every time read everything, add a line, and write everything back.

The third limitation is robustness. Any file write is a potential risk of “we did not manage to finish writing, and the file became empty/corrupted”. Today we are not digging into that topic in detail (otherwise we would suddenly end up discussing reliable write protocols), but just remember: WriteFile is convenient, however “convenient” does not always mean “100% safe”.

7. We integrate ReadFile/WriteFile into a TODO app

Now we will do what is usually done in learning projects: add a “store tasks in a file” layer. We will keep tasks as plain text: one line — one task. No JSON, no databases, no magic. Our goal is to reinforce file handling, not invent our own Notion.

Imagine that the path to the file is already built (for example, via filepath.Join from the previous lecture). Next, we want two functions: loadTasks and saveTasks.

loadText: read a file and return a string

Let us start with a super-simple function: read the file in full as text.

package main

import (
	"fmt"
	"os"
)

func loadText(path string) (string, error) {
	b, err := os.ReadFile(path)
	if err != nil {
		return "", fmt.Errorf("read %q: %w", path, err)
	}
	return string(b), nil
}

Pay attention to %w: we added context, but did not lose the cause of the error. This is an important Go-code habit: errors are “bubbled up” with context, not swept under the rug.

Parsing tasks from text: one line — one task

Now we turn the text into an array of tasks. Here we use strings.Split and tidy the strings up a little.

package main

import (
	"strings"
)

func parseTasks(text string) []string {
	text = strings.TrimSpace(text)
	if text == "" {
		return nil
	}
	return strings.Split(text, "\n")
}

Here we deliberately return nil for an empty result: this is a normal practice for slices. The only important thing is to be consistent.

saveText: write a string in full

We also make writing textual. Notice: writing is []byte(text).

package main

import (
	"fmt"
	"os"
)

func saveText(path string, text string) error {
	if err := os.WriteFile(path, []byte(text), 0644); err != nil {
		return fmt.Errorf("write %q: %w", path, err)
	}
	return nil
}

Glue the tasks back into text

To save tasks, we need to assemble them back into one string. This is simple.

package main

import (
	"strings"
)

func formatTasks(tasks []string) string {
	if len(tasks) == 0 {
		return ""
	}
	return strings.Join(tasks, "\n") + "\n"
}

Adding "\n" at the end is a small “text culture”: many tools and people like it when a text file ends with a newline.

8. Mini-scenario: add a task through read → parse → append → write

Now let us assemble a small piece of “business logic” (though it sounds grand): add a task and save the file.

package main

import (
	"fmt"
)

func addTask(path string, title string) error {
	text, err := loadText(path)
	if err != nil {
		return err
	}

	tasks := parseTasks(text)
	tasks = append(tasks, title)

	return saveText(path, formatTasks(tasks))
}

There is a very important thought here: we work with the file as the “state of the application”. We loaded the state, changed it, saved it. It is like a game where you loaded a save, picked up a new item, and saved the game again.

For now we are not discussing “what if the file does not exist” or “what if permissions are insufficient” — of course we will handle that, but we are not turning every function into a 40-page novel about error drama. At this stage, it is important to reinforce the very approach of reading and writing in full.

Data flow diagram

When the code starts growing, it helps the brain to see the “pipe” through which the data flows. Here is our approach diagram:

flowchart TD
    A[File on disk] -->|os.ReadFile| B["[]byte"]
    B -->|"string(b)"| C[Text]
    C -->|parseTasks| D["[]string tasks"]
    D -->|append/changes| E["[]string tasks"]
    E -->|formatTasks| F[Text]
    F -->|"[]byte(text)"| G["[]byte"]
    G -->|os.WriteFile| H[File on disk]

If you see this diagram and understand what happens at each step, then the topic is being learned correctly.

9. Typical mistakes

Mistake #1: use os.ReadFile “just in case” for large files.
When you first learn ReadFile, it seems universal: one line — and you have the whole file. The problem is that the “whole file” may turn out to be too large. As a result, the program starts consuming memory aggressively and suddenly becomes very slow or crashes. If you cannot guarantee the size in advance, that is a signal that the “all at once” approach may be dangerous.

Mistake #2: expect os.WriteFile to “append to the end”.
For beginners, WriteFile often sounds in the head like “write to a file” in general. But in reality it means “write in full” with content overwrite. If you need to “append a line to the end”, WriteFile is not your tool: it will recreate the file and may erase what was there. Even if you read the file first, that would be extra work and a risk of errors.

Mistake #3: forget about string ↔ []byte conversions.
ReadFile returns []byte, not string. WriteFile accepts []byte, not string. Because of this, people sometimes write strange constructions or try to “stuff the string in somehow”. The correct way is simple and honest: text := string(b) when reading text and []byte(text) when writing.

Mistake #4: lose error context when returning upward.
If you return the error simply as return err, then at the top level you will see “permission denied” without understanding “where exactly and what were we trying to do”. It is better to add context with fmt.Errorf("read %q: %w", path, err) — then the error remains recognizable and becomes clearer to a person. The habit of writing explicit if err != nil checks and propagating errors with context is a basic part of Go style.

Mistake #5: assume that writing always “completed and saved”.
Sometimes it seems: “well, WriteFile returned nil, so everything is rock solid.” In practice, writing to disk can be a source of many problems: the path may be wrong, the directory may not exist, permissions may be insufficient, the disk may be full. We are not turning this lecture into an encyclopedia of file disasters, but it is important to remember: writing is an operation that can honestly return an error, and it must be handled, not ignored.

1
과제
Go SELF, 레벨 39, 레슨 2
잠금
바이트 카운터
바이트 카운터
1
과제
Go SELF, 레벨 39, 레슨 2
잠금
텍스트 확대 검사
텍스트 확대 검사
1
과제
Go SELF, 레벨 39, 레슨 2
잠금
문서 프레임
문서 프레임
1
과제
Go SELF, 레벨 39, 레슨 2
잠금
파일 보고서
파일 보고서
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION