os#

File Operations#

The os package provides a platform-independent interface to operating system functionality, modeled directly on the UNIX system call interface (see File I/O).

os.OpenFile#

General-purpose function to open or create files, identical to POSIX open(pathname, flags, mode).

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

Flags (os package)#

Bitwise OR combinations of access modes and status flags:

Go FlagPOSIX FlagDescription
os.O_RDONLYO_RDONLYOpen for read-only
os.O_WRONLYO_WRONLYOpen for write-only
os.O_RDWRO_RDWROpen for reading and writing
os.O_CREATEO_CREATCreate file if it does not exist (perm required)
os.O_EXCLO_EXCLUsed with O_CREATE; fail if file already exists
os.O_TRUNCO_TRUNCTruncate file length to zero on open
os.O_APPENDO_APPENDAppend data to the end of the file on write
os.O_SYNCO_SYNCOpen for synchronous I/O

Convenience Wrappers (os.Open & os.Create)#

os.Open and os.Create wrap os.OpenFile with standard POSIX defaults.

// Open opens the named file for reading (O_RDONLY)
func Open(name string) (*File, error) {
    return OpenFile(name, O_RDONLY, 0)
}

// Create creates or truncates the named file (O_RDWR|O_CREATE|O_TRUNC, 0666)
func Create(name string) (*File, error) {
    return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666)
}

Standard File Descriptors#

Pre-defined *os.File handles for standard streams:

StreamGo VariablePOSIX FD
Standard Inputos.StdinSTDIN_FILENO (0)
Standard Outputos.StdoutSTDOUT_FILENO (1)
Standard Erroros.StderrSTDERR_FILENO (2)
// Access underlying integer file descriptor
fd := file.Fd() // returns uintptr

# go os