Standard library / os

os.OpenFile()

Opens with explicit access and creation flags; permission bits apply only on creation, before umask. Example uses a disposable temporary workspace. Expected stdout: 'abcd\n'.

Formal Syntax & Structure

go syntaxgo
func OpenFile(name string, flag int, perm FileMode) (*File, error)

Parameters & Attributes

NameTypeDescription
namestringName or pathname of the target.
flagintAccess mode and additional open flags.
permFileModeRequested permissions before umask when creating.

Return Value

(*File, error)

Opens with explicit access and creation flags; permission bits apply only on creation, before umask.

Working Example

Example Snippetgo
package main
import (  "fmt"  "os")
func check(e error) {  if e != nil {    panic(e)  }}func seed() { check(os.WriteFile("a.txt", []byte("abc"), 0600)) }func workspace() func() {  root, e := os.MkdirTemp("", "bytemind-go-")  check(e)  old, e := os.Getwd()  check(e)  check(os.Chdir(root))  return func() { check(os.Chdir(old)); check(os.RemoveAll(root)) }}func main() {  defer workspace()()  seed()  f, e := os.OpenFile("a.txt", os.O_APPEND|os.O_WRONLY, 0600)  check(e)  _, e = f.WriteString("d")  check(e)  check(f.Close())  b, e := os.ReadFile("a.txt")  check(e)  fmt.Println(string(b))}
Go Reference