Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Errors, I/O and Files

Go os.Open(), os.Create() and os.OpenFile() functions

Reference for Go os.Open, os.Create and os.OpenFile: flags, permissions, reading and writing with *os.File, Seek, Close and Sync, with common mistakes.

os.Open opens an existing file for reading. os.Create creates a file (or truncates an existing one) and opens it for reading and writing. os.OpenFile is the general form behind both: you choose the access mode, creation behaviour and permissions with flags.

All three return an *os.File, which implements io.Reader, io.Writer, io.Seeker, io.Closer and more. A file is an operating-system resource, so every successful open must be matched by a Close.

Go
f, err := os.Open("data.txt")
if err != nil {
	return err
}
defer f.Close()

Try it

Go Create, write, seek and read

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go OpenFile flags: append and exclusive create

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
func Open(name string) (*File, error)
func Create(name string) (*File, error)
func OpenFile(name string, flag int, perm FileMode) (*File, error)
Function Equivalent OpenFile call
Open(name) OpenFile(name, O_RDONLY, 0)
Create(name) OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0o666)

Flags are combined with |. Exactly one of O_RDONLY, O_WRONLY or O_RDWR is required; add O_CREATE, O_EXCL, O_APPEND, O_TRUNC or O_SYNC as needed.

Frequently used *File methods:

Method Description
Read, ReadAt Sequential and positional reads.
Write, WriteString, WriteAt Writes; WriteAt fails on files opened with O_APPEND.
Seek(offset, whence) Moves the cursor (io.SeekStart, SeekCurrent, SeekEnd).
Stat() Returns fs.FileInfo (size, mode, modification time).
Sync() Flushes data to stable storage.
Truncate(size) Changes the file size.
ReadDir(n), Readdirnames(n) Lists directory contents when the file is a directory.
Close() Releases the handle; calling it twice returns os.ErrClosed.

Errors: a *fs.PathError (Op is "open") wrapping fs.ErrNotExist, fs.ErrPermission, fs.ErrExist and so on.

Usage notes

  • defer f.Close() after the error check, never before: f is nil when opening failed.
  • For files you write, check Close's error. On some file systems (notably network ones) a write error only surfaces then.
  • Create destroys existing content immediately. Use O_EXCL if overwriting would be a bug.
  • Open in a loop with care: deferring Close inside a loop keeps every file open until the function returns. Wrap the body in a function or close explicitly.
  • Stdin, Stdout and Stderr are ordinary *os.File values (os.Stdin and friends).
  • Do not rely on finalizers to close files; the garbage collector eventually closes them, but timing is unspecified and descriptors are limited.
  • Buffering: a *os.File is unbuffered, so thousands of tiny writes mean thousands of system calls. Wrap it in bufio.NewWriter (and flush before closing).
  • Sync is needed only for durability against power loss, and is slow.
  • Since Go 1.24, os.Root offers Open, Create and OpenFile methods that cannot escape a chosen directory, useful for untrusted paths.