liveBook · Manning

Os.OpenFile

As explained in Learn Go with Pocket-Sized Projects

os.OpenFile is a Go os-package function that opens or creates a file according to supplied access flags and permissions.

os.OpenFile opens or creates a file with caller-selected access flags and permissions. It is more general than os.Open and os.Create, but most read-only or ordinary creation tasks can use those simpler functions. section 3.1.2

Use os.OpenFile when the file operation requires control over:

  • Appending without discarding existing contents. section 3.1.2
  • Creating a file with permissions different from os.Create’s default. section 3.1.2
  • Combining access flags such as os.O_APPEND, os.O_CREATE, and os.O_WRONLY. section 3.1.2

Append to a file

f, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666) if err != nil { return err } defer f.Close() // Write data to f without erasing existing contents. section 3.1.2

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains the main use cases and flag combination, while deferring the complete flag list to Go documentation.
Examples
Demonstrates appending with os.O_APPEND|os.O_CREATE|os.O_WRONLY and closing the returned file.
What it assumes
Assumes familiarity with Go functions, error returns, file descriptors, and the os package.
What you can do after
Apply it via Go’s os package to append or create files without unintentionally truncating existing contents.
How it connects
Connects os.OpenFile with os.Open, os.Create, file descriptors, access flags, permissions, and error values.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.