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 Flag | POSIX Flag | Description |
|---|---|---|
os.O_RDONLY | O_RDONLY | Open for read-only |
os.O_WRONLY | O_WRONLY | Open for write-only |
os.O_RDWR | O_RDWR | Open for reading and writing |
os.O_CREATE | O_CREAT | Create file if it does not exist (perm required) |
os.O_EXCL | O_EXCL | Used with O_CREATE; fail if file already exists |
os.O_TRUNC | O_TRUNC | Truncate file length to zero on open |
os.O_APPEND | O_APPEND | Append data to the end of the file on write |
os.O_SYNC | O_SYNC | Open 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:
| Stream | Go Variable | POSIX FD |
|---|---|---|
| Standard Input | os.Stdin | STDIN_FILENO (0) |
| Standard Output | os.Stdout | STDOUT_FILENO (1) |
| Standard Error | os.Stderr | STDERR_FILENO (2) |
// Access underlying integer file descriptor
fd := file.Fd() // returns uintptr