GoFile IoBeginner

os.ReadFile() / os.WriteFile()

Convenience functions for reading the entire content of a file into a byte slice or writing a byte slice to a file, handling opening and closing automatically.

Review the syntaxStudy the examplesOpen the coding app
os.ReadFile(name string) ([]byte, error)
os.WriteFile(name string, data []byte, perm os.FileMode) error

This static page keeps the syntax and examples indexed for search, while the coding app handles interactive exploration and saved references.

What it does

Overview

Convenience functions for reading the entire content of a file into a byte slice or writing a byte slice to a file, handling opening and closing automatically.

The `os.ReadFile()` and `os.WriteFile()` functions provide simplified, high-level interfaces for common file I/O operations. `os.ReadFile(name string)` reads the named file and returns its entire content as a byte slice. It handles opening, reading, and closing the file automatically. This is ideal for reading small to moderately sized files where loading the entire content into memory is acceptable. For very large files, it's more memory-efficient to use `os.Open()` and stream the data using an `io.Reader`. `os.WriteFile(name string, data []byte, perm os.FileMode)` writes the `data` byte slice to the named file. If the file does not exist, `WriteFile` creates it with the given permissions (`perm`). If the file already exists, it is truncated before writing. Like `ReadFile`, it handles opening, writing, and closing the file automatically. The `perm` argument specifies the file's permission bits (e.g., `0644` for read/write by owner, read-only by group/others). Both functions return an `error` if the operation fails (e.g., file not found, permission denied, disk full). These convenience functions are excellent for quick scripts or applications where the entire file content can be managed in memory, as they significantly reduce boilerplate code compared to manual `os.Open`/`Create` and `file.Read`/`Write` operations with `defer file.Close()`. However, for fine-grained control, error handling during streaming, or very large files, the lower-level `os.Open`/`Create` methods are more appropriate.

Quick reference

Syntax

os.ReadFile(name string) ([]byte, error)
os.WriteFile(name string, data []byte, perm os.FileMode) error

Inputs

Parameters

namestring · The path to the file.
data[]byte · The byte slice to write to the file.
permos.FileMode · The file permissions to use if creating the file (e.g., 0644).

See it in practice

Examples

1

Reading an entire file into memory

package main

import (
	"fmt"
	"os"
)

func main() {
	// Create a dummy file for reading
	dummyFile, _ := os.Create("readall.txt")
	dummyFile.WriteString("Line 1\nLine 2\nLine 3")
	dummyFile.Close()

	data, err := os.ReadFile("readall.txt")
	if err != nil {
		fmt.Println("Error reading file:", err)
		return
	}
	fmt.Println("File content:\n", string(data))

	os.Remove("readall.txt") // Clean up
}
Output:
File content: Line 1 Line 2 Line 3

`os.ReadFile` reads the entire content of `readall.txt` into a byte slice, which is then converted to a string and printed.

2

Writing a byte slice to a file

package main

import (
	"fmt"
	"os"
)

func main() {
	content := []byte("This is some content to write.\nAnother line.")
	err := os.WriteFile("writeall.txt", content, 0644)
	if err != nil {
		fmt.Println("Error writing file:", err)
		return
	}
	fmt.Println("Successfully wrote to writeall.txt")

	// Verify content by reading it back
	readData, _ := os.ReadFile("writeall.txt")
	fmt.Println("Read back:\n", string(readData))

	os.Remove("writeall.txt") // Clean up
}
Output:
Successfully wrote to writeall.txt Read back: This is some content to write. Another line.

`os.WriteFile` creates `writeall.txt` (or truncates if it exists) with `0644` permissions and writes the `content` byte slice to it. The content is then read back for verification.

3

Handling errors with os.ReadFile

package main

import (
	"errors"
	"fmt"
	"os"
)

func main() {
	_, err := os.ReadFile("nonexistent_file.txt")
	if err != nil {
		fmt.Println("Error reading file:", err)
		if errors.Is(err, os.ErrNotExist) {
			fmt.Println("Specific error: File does not exist.")
		} else {
			fmt.Println("Specific error: Another file error occurred.")
		}
	}

	// Simulate permission denied (might require running as non-root on a protected file)
	// err = os.WriteFile("/root/no_permission.txt", []byte("test"), 0644)
	// if err != nil {
	// 	fmt.Println("Error writing to protected path:", err)
	// 	if errors.Is(err, os.ErrPermission) {
	// 		fmt.Println("Specific error: Permission denied.")
	// 	}
	// }
}
Output:
Error reading file: open nonexistent_file.txt: no such file or directory Specific error: File does not exist.

This example demonstrates how to check for specific file I/O errors like `os.ErrNotExist` using `errors.Is` when `os.ReadFile` fails.

Debug faster

Common Errors

1

Memory Exhaustion for Large Files

Cause: `os.ReadFile()` reads the entire file into memory. For extremely large files (e.g., several gigabytes), this can exhaust available RAM and cause the program to crash.

Fix: For very large files, use `os.Open()` to get an `*os.File` and then read the content in chunks using `file.Read()` or process it as a stream, rather than loading it all at once.

package main

import (
	"fmt"
	"os"
)

func main() {
	// Imagine 'huge_log.txt' is 10GB
	// This would likely crash the program with an out-of-memory error
	// data, err := os.ReadFile("huge_log.txt")
	// if err != nil {
	// 	fmt.Println("Error reading huge file:", err)
	// 	return
	// }
	fmt.Println("Reading extremely large files with os.ReadFile can cause OOM errors.")
	fmt.Println("Use streaming for large files.")
}

Runtime support

Compatibility

Go RuntimeN/AGo 1.16+

Source: Go Standard Library Documentation

Common questions

Frequently Asked Questions

Convenience functions for reading the entire content of a file into a byte slice or writing a byte slice to a file, handling opening and closing automatically.

name: The path to the file. data: The byte slice to write to the file. perm: The file permissions to use if creating the file (e.g., 0644).

Memory Exhaustion for Large Files: For very large files, use `os.Open()` to get an `*os.File` and then read the content in chunks using `file.Read()` or process it as a stream, rather than loading it all at once.