File I/O Toolkit

Open with explicit flags, seek to an offset, read the remainder, then confine all I/O to one directory with os.Root (Go 1.24+) so a ../ climb fails.

package main

import (
	"fmt"
	"io"
	"os"
	"path/filepath"
)

func main() {
	dir, _ := os.MkdirTemp("", "fileio")
	defer os.RemoveAll(dir)
	path := filepath.Join(dir, "data.txt")

	// Write-only, create if missing, append to the end, mode 0644.
	f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
	if err != nil {
		fmt.Println("open:", err)
		return
	}
	f.WriteString("hello ")
	f.WriteString("systems\n")
	f.Close()

	// Reopen, seek past "hello ", read what's left.
	f, _ = os.Open(path)
	defer f.Close()
	f.Seek(6, io.SeekStart)
	rest, _ := io.ReadAll(f)
	fmt.Printf("from offset 6: %q\n", rest) // from offset 6: "systems\n"

	// os.Root confines every operation to dir and blocks path escapes.
	root, err := os.OpenRoot(dir)
	if err != nil {
		fmt.Println("OpenRoot:", err)
		return
	}
	defer root.Close()

	if _, err := root.Open("../../etc/passwd"); err != nil {
		fmt.Println("escape blocked:", err)
		// escape blocked: openat ../../etc/passwd: path escapes from parent
	}
}

Save the code as main.go and run it:

go run main.go

Expected output:

from offset 6: "systems\n"
escape blocked: openat ../../etc/passwd: path escapes from parent

os.Root requires Go 1.24 or newer.

💻 Run locally

Copy the code above and run it on your machine

© 2026 ByteLearn.dev. Free courses for developers. · Privacy