All packages

os

import "os"

Package os provides a platform-independent interface to operating system functionality. The design is Unix-like, although the error handling is Go-like; failing calls return values of type error rather than error numbers. Often, more information is available within the error. For example, if a call that takes a file name fails, such as [Open] or [Stat], the error will include the failing file name when printed and will be of type [*PathError], which may be unpacked for more information. The ...

Go 1.26.1

Constants

const DevNull = "/dev/null"

DevNull is the name of the operating system's “null device.” On Unix-like systems, it is "/dev/null"; on Windows, "NUL".

os/file_unix.go:242

const (
	// The single letters are the abbreviations
	// used by the String method's formatting.
	ModeDir        = fs.ModeDir        // d: is a directory
	ModeAppend     = fs.ModeAppend     // a: a...

The defined file mode bits are the most significant bits of the [FileMode]. The nine least-significant bits are the standard Unix rwxrwxrwx permissions. The values of these bits should be considered part of the public API and may be used in wire protocols or disk representations: they must not be changed, although new bits might be added.

os/types.go:41

const (
	// The single letters are the abbreviations
	// used by the String method's formatting.
	ModeDir        = fs.ModeDir        // d: is a directory
	ModeAppend     = fs.ModeAppend     // a: a...

The defined file mode bits are the most significant bits of the [FileMode]. The nine least-significant bits are the standard Unix rwxrwxrwx permissions. The values of these bits should be considered part of the public API and may be used in wire protocols or disk representations: they must not be changed, although new bits might be added.

os/types.go:50

const (
	// The single letters are the abbreviations
	// used by the String method's formatting.
	ModeDir        = fs.ModeDir        // d: is a directory
	ModeAppend     = fs.ModeAppend     // a: a...

The defined file mode bits are the most significant bits of the [FileMode]. The nine least-significant bits are the standard Unix rwxrwxrwx permissions. The values of these bits should be considered part of the public API and may be used in wire protocols or disk representations: they must not be changed, although new bits might be added.

os/types.go:45

const (
	// The single letters are the abbreviations
	// used by the String method's formatting.
	ModeDir        = fs.ModeDir        // d: is a directory
	ModeAppend     = fs.ModeAppend     // a: a...

The defined file mode bits are the most significant bits of the [FileMode]. The nine least-significant bits are the standard Unix rwxrwxrwx permissions. The values of these bits should be considered part of the public API and may be used in wire protocols or disk representations: they must not be changed, although new bits might be added.

os/types.go:40

const (
	// The single letters are the abbreviations
	// used by the String method's formatting.
	ModeDir        = fs.ModeDir        // d: is a directory
	ModeAppend     = fs.ModeAppend     // a: a...

The defined file mode bits are the most significant bits of the [FileMode]. The nine least-significant bits are the standard Unix rwxrwxrwx permissions. The values of these bits should be considered part of the public API and may be used in wire protocols or disk representations: they must not be changed, although new bits might be added.

os/types.go:42

const (
	// The single letters are the abbreviations
	// used by the String method's formatting.
	ModeDir        = fs.ModeDir        // d: is a directory
	ModeAppend     = fs.ModeAppend     // a: a...

The defined file mode bits are the most significant bits of the [FileMode]. The nine least-significant bits are the standard Unix rwxrwxrwx permissions. The values of these bits should be considered part of the public API and may be used in wire protocols or disk representations: they must not be changed, although new bits might be added.

os/types.go:52

const (
	// The single letters are the abbreviations
	// used by the String method's formatting.
	ModeDir        = fs.ModeDir        // d: is a directory
	ModeAppend     = fs.ModeAppend     // a: a...

The defined file mode bits are the most significant bits of the [FileMode]. The nine least-significant bits are the standard Unix rwxrwxrwx permissions. The values of these bits should be considered part of the public API and may be used in wire protocols or disk representations: they must not be changed, although new bits might be added.

os/types.go:46

const (
	// The single letters are the abbreviations
	// used by the String method's formatting.
	ModeDir        = fs.ModeDir        // d: is a directory
	ModeAppend     = fs.ModeAppend     // a: a...

The defined file mode bits are the most significant bits of the [FileMode]. The nine least-significant bits are the standard Unix rwxrwxrwx permissions. The values of these bits should be considered part of the public API and may be used in wire protocols or disk representations: they must not be changed, although new bits might be added.

os/types.go:57

const (
	// The single letters are the abbreviations
	// used by the String method's formatting.
	ModeDir        = fs.ModeDir        // d: is a directory
	ModeAppend     = fs.ModeAppend     // a: a...

The defined file mode bits are the most significant bits of the [FileMode]. The nine least-significant bits are the standard Unix rwxrwxrwx permissions. The values of these bits should be considered part of the public API and may be used in wire protocols or disk representations: they must not be changed, although new bits might be added.

os/types.go:49

const (
	// The single letters are the abbreviations
	// used by the String method's formatting.
	ModeDir        = fs.ModeDir        // d: is a directory
	ModeAppend     = fs.ModeAppend     // a: a...

The defined file mode bits are the most significant bits of the [FileMode]. The nine least-significant bits are the standard Unix rwxrwxrwx permissions. The values of these bits should be considered part of the public API and may be used in wire protocols or disk representations: they must not be changed, although new bits might be added.

os/types.go:48

const (
	// The single letters are the abbreviations
	// used by the String method's formatting.
	ModeDir        = fs.ModeDir        // d: is a directory
	ModeAppend     = fs.ModeAppend     // a: a...

The defined file mode bits are the most significant bits of the [FileMode]. The nine least-significant bits are the standard Unix rwxrwxrwx permissions. The values of these bits should be considered part of the public API and may be used in wire protocols or disk representations: they must not be changed, although new bits might be added.

os/types.go:47

const (
	// The single letters are the abbreviations
	// used by the String method's formatting.
	ModeDir        = fs.ModeDir        // d: is a directory
	ModeAppend     = fs.ModeAppend     // a: a...

The defined file mode bits are the most significant bits of the [FileMode]. The nine least-significant bits are the standard Unix rwxrwxrwx permissions. The values of these bits should be considered part of the public API and may be used in wire protocols or disk representations: they must not be changed, although new bits might be added.

os/types.go:51

const (
	// The single letters are the abbreviations
	// used by the String method's formatting.
	ModeDir        = fs.ModeDir        // d: is a directory
	ModeAppend     = fs.ModeAppend     // a: a...

The defined file mode bits are the most significant bits of the [FileMode]. The nine least-significant bits are the standard Unix rwxrwxrwx permissions. The values of these bits should be considered part of the public API and may be used in wire protocols or disk representations: they must not be changed, although new bits might be added.

os/types.go:43

const (
	// The single letters are the abbreviations
	// used by the String method's formatting.
	ModeDir        = fs.ModeDir        // d: is a directory
	ModeAppend     = fs.ModeAppend     // a: a...

The defined file mode bits are the most significant bits of the [FileMode]. The nine least-significant bits are the standard Unix rwxrwxrwx permissions. The values of these bits should be considered part of the public API and may be used in wire protocols or disk representations: they must not be changed, although new bits might be added.

os/types.go:55

const (
	// Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
	O_RDONLY int = syscall.O_RDONLY // open the file read-only.
	O_WRONLY int = syscall.O_WRONLY // open the file write-only...

Flags to OpenFile wrapping those of the underlying system. Not all flags may be implemented on a given system.

os/file.go:85

const (
	// Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
	O_RDONLY int = syscall.O_RDONLY // open the file read-only.
	O_WRONLY int = syscall.O_WRONLY // open the file write-only...

Flags to OpenFile wrapping those of the underlying system. Not all flags may be implemented on a given system.

os/file.go:86

const (
	// Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
	O_RDONLY int = syscall.O_RDONLY // open the file read-only.
	O_WRONLY int = syscall.O_WRONLY // open the file write-only...

Flags to OpenFile wrapping those of the underlying system. Not all flags may be implemented on a given system.

os/file.go:87

const (
	// Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
	O_RDONLY int = syscall.O_RDONLY // open the file read-only.
	O_WRONLY int = syscall.O_WRONLY // open the file write-only...

Flags to OpenFile wrapping those of the underlying system. Not all flags may be implemented on a given system.

os/file.go:81

const (
	// Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
	O_RDONLY int = syscall.O_RDONLY // open the file read-only.
	O_WRONLY int = syscall.O_WRONLY // open the file write-only...

Flags to OpenFile wrapping those of the underlying system. Not all flags may be implemented on a given system.

os/file.go:83

const (
	// Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
	O_RDONLY int = syscall.O_RDONLY // open the file read-only.
	O_WRONLY int = syscall.O_WRONLY // open the file write-only...

Flags to OpenFile wrapping those of the underlying system. Not all flags may be implemented on a given system.

os/file.go:88

const (
	// Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
	O_RDONLY int = syscall.O_RDONLY // open the file read-only.
	O_WRONLY int = syscall.O_WRONLY // open the file write-only...

Flags to OpenFile wrapping those of the underlying system. Not all flags may be implemented on a given system.

os/file.go:89

const (
	// Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
	O_RDONLY int = syscall.O_RDONLY // open the file read-only.
	O_WRONLY int = syscall.O_WRONLY // open the file write-only...

Flags to OpenFile wrapping those of the underlying system. Not all flags may be implemented on a given system.

os/file.go:82

const (
	PathSeparator     = '/' // OS-specific path separator
	PathListSeparator = ':' // OS-specific path list separator
)

os/path_unix.go:11

const (
	PathSeparator     = '/' // OS-specific path separator
	PathListSeparator = ':' // OS-specific path list separator
)

os/path_unix.go:10

const (
	SEEK_SET int = 0 // seek relative to the origin of the file
	SEEK_CUR int = 1 // seek relative to the current offset
	SEEK_END int = 2 // seek relative to the end
)

Seek whence values. Deprecated: Use io.SeekStart, io.SeekCurrent, and io.SeekEnd.

os/file.go:97

const (
	SEEK_SET int = 0 // seek relative to the origin of the file
	SEEK_CUR int = 1 // seek relative to the current offset
	SEEK_END int = 2 // seek relative to the end
)

Seek whence values. Deprecated: Use io.SeekStart, io.SeekCurrent, and io.SeekEnd.

os/file.go:98

const (
	SEEK_SET int = 0 // seek relative to the origin of the file
	SEEK_CUR int = 1 // seek relative to the current offset
	SEEK_END int = 2 // seek relative to the end
)

Seek whence values. Deprecated: Use io.SeekStart, io.SeekCurrent, and io.SeekEnd.

os/file.go:96

Variables

var Args []string

Args hold the command-line arguments, starting with the program name.

os/proc.go:16

var (
	// ErrInvalid indicates an invalid argument.
	// Methods on File will return this error when the receiver is nil.
	ErrInvalid = fs.ErrInvalid // "invalid argument"

	ErrPermission = fs.ErrPe...

Portable analogs of some common system call errors. Errors returned from this package may be tested against these errors with [errors.Is].

os/error.go:24

var (
	// ErrInvalid indicates an invalid argument.
	// Methods on File will return this error when the receiver is nil.
	ErrInvalid = fs.ErrInvalid // "invalid argument"

	ErrPermission = fs.ErrPe...

Portable analogs of some common system call errors. Errors returned from this package may be tested against these errors with [errors.Is].

os/error.go:27

var (
	// ErrInvalid indicates an invalid argument.
	// Methods on File will return this error when the receiver is nil.
	ErrInvalid = fs.ErrInvalid // "invalid argument"

	ErrPermission = fs.ErrPe...

Portable analogs of some common system call errors. Errors returned from this package may be tested against these errors with [errors.Is].

os/error.go:22

var (
	// ErrInvalid indicates an invalid argument.
	// Methods on File will return this error when the receiver is nil.
	ErrInvalid = fs.ErrInvalid // "invalid argument"

	ErrPermission = fs.ErrPe...

Portable analogs of some common system call errors. Errors returned from this package may be tested against these errors with [errors.Is].

os/error.go:19

var (
	// ErrInvalid indicates an invalid argument.
	// Methods on File will return this error when the receiver is nil.
	ErrInvalid = fs.ErrInvalid // "invalid argument"

	ErrPermission = fs.ErrPe...

Portable analogs of some common system call errors. Errors returned from this package may be tested against these errors with [errors.Is].

os/error.go:26

var (
	// ErrProcessDone indicates a [Process] has finished.
	ErrProcessDone = errors.New("os: process already finished")

	// ErrNoHandle indicates a [Process] does not have a handle.
	ErrNoHandle...

os/exec.go:23

var (
	// ErrInvalid indicates an invalid argument.
	// Methods on File will return this error when the receiver is nil.
	ErrInvalid = fs.ErrInvalid // "invalid argument"

	ErrPermission = fs.ErrPe...

Portable analogs of some common system call errors. Errors returned from this package may be tested against these errors with [errors.Is].

os/error.go:23

var (
	// ErrInvalid indicates an invalid argument.
	// Methods on File will return this error when the receiver is nil.
	ErrInvalid = fs.ErrInvalid // "invalid argument"

	ErrPermission = fs.ErrPe...

Portable analogs of some common system call errors. Errors returned from this package may be tested against these errors with [errors.Is].

os/error.go:21

var (
	// ErrProcessDone indicates a [Process] has finished.
	ErrProcessDone = errors.New("os: process already finished")

	// ErrNoHandle indicates a [Process] does not have a handle.
	ErrNoHandle...

os/exec.go:19

var (
	Stdin  = NewFile(uintptr(syscall.Stdin), "/dev/stdin")
	Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout")
	Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr")
)

Stdin, Stdout, and Stderr are open Files pointing to the standard input, standard output, and standard error file descriptors. Note that the Go runtime writes to standard error for panics and crashes; closing Stderr may cause those messages to go elsewhere, perhaps to a file opened later.

os/file.go:74

var (
	Stdin  = NewFile(uintptr(syscall.Stdin), "/dev/stdin")
	Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout")
	Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr")
)

Stdin, Stdout, and Stderr are open Files pointing to the standard input, standard output, and standard error file descriptors. Note that the Go runtime writes to standard error for panics and crashes; closing Stderr may cause those messages to go elsewhere, perhaps to a file opened later.

os/file.go:72

var (
	Stdin  = NewFile(uintptr(syscall.Stdin), "/dev/stdin")
	Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout")
	Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr")
)

Stdin, Stdout, and Stderr are open Files pointing to the standard input, standard output, and standard error file descriptors. Note that the Go runtime writes to standard error for panics and crashes; closing Stderr may cause those messages to go elsewhere, perhaps to a file opened later.

os/file.go:73

Functions

func Chdir(dir string) error

Chdir changes the current working directory to the named directory. If there is an error, it will be of type [*PathError].

os/file.go:361

func Chmod(name string, mode FileMode) error

Chmod changes the mode of the named file to mode. If the file is a symbolic link, it changes the mode of the link's target. If there is an error, it will be of type [*PathError]. A different subset of the mode bits are used, depending on the operating system. On Unix, the mode's permission bits, [ModeSetuid], [ModeSetgid], and [ModeSticky] are used. On Windows, only the 0o200 bit (owner writable) of mode is used; it controls whether the file's read-only attribute is set or cleared. The oth...

os/file.go:644

func Chown(name string, uid int, gid int) error

Chown changes the numeric uid and gid of the named file. If the file is a symbolic link, it changes the uid and gid of the link's target. A uid or gid of -1 means to not change that value. If there is an error, it will be of type [*PathError]. On Windows or Plan 9, Chown always returns the [syscall.EWINDOWS] or [syscall.EPLAN9] error, wrapped in [*PathError].

os/file_posix.go:105

func Chtimes(name string, atime time.Time, mtime time.Time) error

Chtimes changes the access and modification times of the named file, similar to the Unix utime() or utimes() functions. A zero [time.Time] value will leave the corresponding file time unchanged. The underlying filesystem may truncate or round the values to a less precise time unit. If there is an error, it will be of type [*PathError].

os/file_posix.go:179

func Clearenv()

Clearenv deletes all environment variables.

os/env.go:133

func CopyFS(dir string, fsys fs.FS) error

CopyFS copies the file system fsys into the directory dir, creating dir if necessary. Files are created with mode 0o666 plus any execute permissions from the source, and directories are created with mode 0o777 (before umask). CopyFS will not overwrite existing files. If a file name in fsys already exists in the destination, CopyFS will return an error such that errors.Is(err, fs.ErrExist) will be true. Symbolic links in dir are followed. New files added to fsys (including if dir is a subd...

os/dir.go:145

func Create(name string) (*File, error)

Create creates or truncates the named file. If the file already exists, it is truncated. If the file does not exist, it is created with mode 0o666 (before umask). If successful, methods on the returned File can be used for I/O; the associated file descriptor has mode [O_RDWR]. The directory containing the file must already exist. If there is an error, it will be of type [*PathError].

os/file.go:399

func CreateTemp(dir string, pattern string) (*File, error)

CreateTemp creates a new temporary file in the directory dir, opens the file for reading and writing, and returns the resulting file. The filename is generated by taking pattern and adding a random string to the end. If pattern includes a "*", the random string replaces the last "*". The file is created with mode 0o600 (before umask). If dir is the empty string, CreateTemp uses the default directory for temporary files, as returned by [TempDir]. Multiple programs or goroutines calling CreateT...

os/tempfile.go:35

func DirFS(dir string) fs.FS

DirFS returns a file system (an fs.FS) for the tree of files rooted at the directory dir. Note that DirFS("/prefix") only guarantees that the Open calls it makes to the operating system will begin with "/prefix": DirFS("/prefix").Open("file") is the same as os.Open("/prefix/file"). So if /prefix/file is a symbolic link pointing outside the /prefix tree, then using DirFS does not stop the access any more than using os.Open does. Additionally, the root of the fs.FS returned for a relative path...

os/file.go:743

func Environ() []string

Environ returns a copy of strings representing the environment, in the form "key=value".

os/env.go:139

func Executable() (string, error)

Executable returns the path name for the executable that started the current process. There is no guarantee that the path is still pointing to the correct executable. If a symlink was used to start the process, depending on the operating system, the result might be the symlink or the path it pointed to. If a stable result is needed, [path/filepath.EvalSymlinks] might help. Executable returns an absolute path unless an error occurred. The main use case is finding resources located relative t...

os/executable.go:18

func Exit(code int)

Exit causes the current program to exit with the given status code. Conventionally, code zero indicates success, non-zero an error. The program terminates immediately; deferred functions are not run. For portability, the status code should be in the range [0, 125].

os/proc.go:62

func Expand(s string, mapping func(...)) string

Expand replaces ${var} or $var in the string based on the mapping function. For example, [os.ExpandEnv](s) is equivalent to [os.Expand](s, [os.Getenv]).

os/env.go:16

func ExpandEnv(s string) string

ExpandEnv replaces ${var} or $var in the string according to the values of the current environment variables. References to undefined variables are replaced by the empty string.

os/env.go:50

func FindProcess(pid int) (*Process, error)

FindProcess looks for a running process by its pid. The [Process] it returns can be used to obtain information about the underlying operating system process. On Unix systems, FindProcess always succeeds and returns a Process for the given pid, regardless of whether the process exists. To test whether the process actually exists, see whether p.Signal(syscall.Signal(0)) reports an error.

os/exec.go:253

func Getegid() int

Getegid returns the numeric effective group id of the caller. On Windows, it returns -1.

os/proc.go:46

func Getenv(key string) string

Getenv retrieves the value of the environment variable named by the key. It returns the value, which will be empty if the variable is not present. To distinguish between an empty value and an unset value, use [LookupEnv].

os/env.go:101

func Geteuid() int

Geteuid returns the numeric effective user id of the caller. On Windows, it returns -1.

os/proc.go:36

func Getgid() int

Getgid returns the numeric group id of the caller. On Windows, it returns -1.

os/proc.go:41

func Getgroups() ([]int, error)

Getgroups returns a list of the numeric ids of groups that the caller belongs to. On Windows, it returns [syscall.EWINDOWS]. See the [os/user] package for a possible alternative.

os/proc.go:52

func Getpagesize() int

Getpagesize returns the underlying system's memory page size.

os/types.go:13

func Getpid() int

Getpid returns the process id of the caller.

os/exec.go:239

func Getppid() int

Getppid returns the process id of the caller's parent.

os/exec.go:242

func Getuid() int

Getuid returns the numeric user id of the caller. On Windows, it returns -1.

os/proc.go:31

func Getwd() (string, error)

Getwd returns an absolute path name corresponding to the current directory. If the current directory can be reached via multiple paths (due to symbolic links), Getwd may return any one of them. On Unix platforms, if the environment variable PWD provides an absolute name, and it is a name of the current directory, it is returned.

os/getwd.go:26

func Hostname() (string, error)

Hostname returns the host name reported by the kernel.

os/sys.go:8

func IsExist(err error) bool

IsExist returns a boolean indicating whether its argument is known to report that a file or directory already exists. It is satisfied by [ErrExist] as well as some syscall errors. This function predates [errors.Is]. It only supports errors returned by the os package. New code should use errors.Is(err, fs.ErrExist).

os/error.go:80

func IsNotExist(err error) bool

IsNotExist returns a boolean indicating whether its argument is known to report that a file or directory does not exist. It is satisfied by [ErrNotExist] as well as some syscall errors. This function predates [errors.Is]. It only supports errors returned by the os package. New code should use errors.Is(err, fs.ErrNotExist).

os/error.go:90

func IsPathSeparator(c uint8) bool

IsPathSeparator reports whether c is a directory separator character.

os/path_unix.go:15

func IsPermission(err error) bool

IsPermission returns a boolean indicating whether its argument is known to report that permission is denied. It is satisfied by [ErrPermission] as well as some syscall errors. This function predates [errors.Is]. It only supports errors returned by the os package. New code should use errors.Is(err, fs.ErrPermission).

os/error.go:100

func IsTimeout(err error) bool

IsTimeout returns a boolean indicating whether its argument is known to report that a timeout occurred. This function predates [errors.Is], and the notion of whether an error indicates a timeout can be ambiguous. For example, the Unix error EWOULDBLOCK sometimes indicates a timeout and sometimes does not. New code should use errors.Is with a value appropriate to the call returning the error, such as [os.ErrDeadlineExceeded].

os/error.go:112

func Lchown(name string, uid int, gid int) error

Lchown changes the numeric uid and gid of the named file. If the file is a symbolic link, it changes the uid and gid of the link itself. If there is an error, it will be of type [*PathError]. On Windows, it always returns the [syscall.EWINDOWS] error, wrapped in [*PathError].

os/file_posix.go:121

func LookupEnv(key string) (string, bool)

LookupEnv retrieves the value of the environment variable named by the key. If the variable is present in the environment the value (which may be empty) is returned and the boolean is true. Otherwise the returned value will be empty and the boolean will be false.

os/env.go:112

func Lstat(name string) (FileInfo, error)

Lstat returns a [FileInfo] describing the named file. If the file is a symbolic link, the returned FileInfo describes the symbolic link. Lstat makes no attempt to follow the link. If there is an error, it will be of type [*PathError]. On Windows, if the file is a reparse point that is a surrogate for another named entity (such as a symbolic link or mounted folder), the returned FileInfo describes the reparse point, and makes no attempt to resolve it.

os/stat.go:24

func Mkdir(name string, perm FileMode) error

Mkdir creates a new directory with the specified name and permission bits (before umask). If there is an error, it will be of type [*PathError].

os/file.go:327

func MkdirAll(path string, perm FileMode) error

MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error. The permission bits perm (before umask) are used for all directories that MkdirAll creates. If path is already a directory, MkdirAll does nothing and returns nil.

os/path.go:19

func MkdirTemp(dir string, pattern string) (string, error)

MkdirTemp creates a new temporary directory in the directory dir and returns the pathname of the new directory. The new directory's name is generated by adding a random string to the end of pattern. If pattern includes a "*", the random string replaces the last "*" instead. The directory is created with mode 0o700 (before umask). If dir is the empty string, MkdirTemp uses the default directory for temporary files, as returned by TempDir. Multiple programs or goroutines calling MkdirTemp simul...

os/tempfile.go:86

func NewFile(fd uintptr, name string) *File

NewFile returns a new [File] with the given file descriptor and name. The returned value will be nil if fd is not a valid file descriptor. NewFile's behavior differs on some platforms: - On Unix, if fd is in non-blocking mode, NewFile will attempt to return a pollable file. - On Windows, if fd is opened for asynchronous I/O (that is, [syscall.FILE_FLAG_OVERLAPPED] has been specified in the [syscall.CreateFile] call), NewFile will attempt to return a pollable file by associating ...

os/file.go:133

func NewSyscallError(syscall string, err error) error

NewSyscallError returns, as an error, a new [SyscallError] with the given system call name and error details. As a convenience, if err is nil, NewSyscallError returns nil.

os/error.go:67

func Open(name string) (*File, error)

Open opens the named file for reading. If successful, methods on the returned file can be used for reading; the associated file descriptor has mode [O_RDONLY]. If there is an error, it will be of type [*PathError].

os/file.go:389

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

OpenFile is the generalized open call; most users will use Open or Create instead. It opens the named file with specified flag ([O_RDONLY] etc.). If the file does not exist, and the [O_CREATE] flag is passed, it is created with mode perm (before umask); the containing directory must exist. If successful, methods on the returned File can be used for I/O. If there is an error, it will be of type [*PathError].

os/file.go:410

func OpenInRoot(dir string, name string) (*File, error)

OpenInRoot opens the file name in the directory dir. It is equivalent to OpenRoot(dir) followed by opening the file in the root. OpenInRoot returns an error if any component of the name references a location outside of dir. See [Root] for details and limitations.

os/root.go:25

func OpenRoot(name string) (*Root, error)

OpenRoot opens the named directory. It follows symbolic links in the directory name. If there is an error, it will be of type [*PathError].

os/root.go:82

func Pipe() (*File, *File, error)

Pipe returns a connected pair of Files; reads from r return bytes written to w. It returns the files and an error, if any.

os/pipe_wasm.go:13

func ReadDir(name string) ([]DirEntry, error)

ReadDir reads the named directory, returning all its directory entries sorted by filename. If an error occurs reading the directory, ReadDir returns the entries it was able to read before the error, along with the error.

os/dir.go:114

func ReadFile(name string) ([]byte, error)

ReadFile reads the named file and returns the contents. A successful call returns err == nil, not err == EOF. Because ReadFile reads the whole file, it does not treat an EOF from Read as an error to be reported.

os/file.go:864

func Remove(name string) error

Remove removes the named file or (empty) directory. If there is an error, it will be of type [*PathError].

os/file_unix.go:357

func RemoveAll(path string) error

RemoveAll removes path and any children it contains. It removes everything it can but returns the first error it encounters. If the path does not exist, RemoveAll returns nil (no error). If there is an error, it will be of type [*PathError].

os/path.go:73

func Rename(oldpath string, newpath string) error

Rename renames (moves) oldpath to newpath. If newpath already exists and is not a directory, Rename replaces it. If newpath already exists and is a directory, Rename returns an error. OS-specific restrictions may apply when oldpath and newpath are in different directories. Even within the same directory, on non-Unix platforms Rename is not an atomic operation. If there is an error, it will be of type *LinkError.

os/file.go:437

func SameFile(fi1 FileInfo, fi2 FileInfo) bool

SameFile reports whether fi1 and fi2 describe the same file. For example, on Unix this means that the device and inode fields of the two underlying structures are identical; on other systems the decision may be based on the path names. SameFile only applies to results returned by this package's [Stat]. It returns false in other cases.

os/types.go:69

func Setenv(key string, value string) error

Setenv sets the value of the environment variable named by the key. It returns an error, if any.

os/env.go:119

func StartProcess(name string, argv []string, attr *ProcAttr) (*Process, error)

StartProcess starts a new process with the program, arguments and attributes specified by name, argv and attr. The argv slice will become [os.Args] in the new process, so it normally starts with the program name. If the calling goroutine has locked the operating system thread with [runtime.LockOSThread] and modified any inheritable OS-level thread state (for example, Linux or Plan 9 name spaces), the new process will inherit the caller's thread state. StartProcess is a low-level interface. ...

os/exec.go:270

func Stat(name string) (FileInfo, error)

Stat returns a [FileInfo] describing the named file. If there is an error, it will be of type [*PathError].

os/stat.go:11

func TempDir() string

TempDir returns the default directory to use for temporary files. On Unix systems, it returns $TMPDIR if non-empty, else /tmp. On Windows, it uses GetTempPath, returning the first non-empty value from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory. On Plan 9, it returns /tmp. The directory is neither guaranteed to exist nor have accessible permissions.

os/file.go:487

func Truncate(name string, size int64) error

Truncate changes the size of the named file. If the file is a symbolic link, it changes the size of the link's target. If there is an error, it will be of type [*PathError].

os/file_unix.go:345

func Unsetenv(key string) error

Unsetenv unsets a single environment variable.

os/env.go:128

func UserCacheDir() (string, error)

UserCacheDir returns the default root directory to use for user-specific cached data. Users should create their own application-specific subdirectory within this one and use that. On Unix systems, it returns $XDG_CACHE_HOME as specified by https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html if non-empty, else $HOME/.cache. On Darwin, it returns $HOME/Library/Caches. On Windows, it returns %LocalAppData%. On Plan 9, it returns $home/lib/cache. If the location cannot ...

os/file.go:504

func UserConfigDir() (string, error)

UserConfigDir returns the default root directory to use for user-specific configuration data. Users should create their own application-specific subdirectory within this one and use that. On Unix systems, it returns $XDG_CONFIG_HOME as specified by https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html if non-empty, else $HOME/.config. On Darwin, it returns $HOME/Library/Application Support. On Windows, it returns %AppData%. On Plan 9, it returns $home/lib. If the loca...

os/file.go:557

func UserHomeDir() (string, error)

UserHomeDir returns the current user's home directory. On Unix, including macOS, it returns the $HOME environment variable. On Windows, it returns %USERPROFILE%. On Plan 9, it returns the $home environment variable. If the expected variable is not set in the environment, UserHomeDir returns either a platform-specific default value or a non-nil error.

os/file.go:605

func WriteFile(name string, data []byte, perm FileMode) error

WriteFile writes data to the named file, creating it if necessary. If the file does not exist, WriteFile creates it with permissions perm (before umask); otherwise WriteFile truncates it before writing, without changing permissions. Since WriteFile requires multiple system calls to complete, a failure mid-operation can leave the file in a partially written state.

os/file.go:932

Types

type DirEntry = fs.DirEntry

A DirEntry is an entry read from a directory (using the [ReadDir] function or a [File.ReadDir] method).

os/dir.go:85

type File struct {
	// contains filtered or unexported fields
}

File represents an open file descriptor. The methods of File are safe for concurrent use.

os/types.go:18

func (f *File) Chdir() error

Chdir changes the current working directory to the file, which must be a directory. If there is an error, it will be of type [*PathError].

os/file_posix.go:204

func (f *File) Chmod(mode FileMode) error

Chmod changes the mode of the file to mode. If there is an error, it will be of type [*PathError].

os/file.go:648

func (f *File) Chown(uid int, gid int) error

Chown changes the numeric uid and gid of the named file. If there is an error, it will be of type [*PathError]. On Windows, it always returns the [syscall.EWINDOWS] error, wrapped in [*PathError].

os/file_posix.go:136

func (f *File) Close() error

Close closes the [File], rendering it unusable for I/O. On files that support [File.SetDeadline], any pending I/O operations will be canceled and return immediately with an [ErrClosed] error. Close will return an error if it has already been called.

os/file_posix.go:19

func (f *File) Fd() uintptr

Fd returns the system file descriptor or handle referencing the open file. If f is closed, the descriptor becomes invalid. If f is garbage collected, a finalizer may close the descriptor, making it invalid; see [runtime.SetFinalizer] for more information on when a finalizer might be run. Do not close the returned descriptor; that could cause a later close of f to close an unrelated descriptor. Fd's behavior differs on some platforms: - On Unix and Windows, [File.SetDeadline] methods will...

os/file.go:722

func (f *File) Name() string

Name returns the name of the file as presented to Open. It is safe to call Name after [Close].

os/file.go:63

func (f *File) Read(b []byte) (int, error)

Read reads up to len(b) bytes from the File and stores them in b. It returns the number of bytes read and any error encountered. At end of file, Read returns 0, io.EOF.

os/file.go:140

func (f *File) ReadAt(b []byte, off int64) (int, error)

ReadAt reads len(b) bytes from the File starting at byte offset off. It returns the number of bytes read and the error, if any. ReadAt always returns a non-nil error when n < len(b). At end of file, that error is io.EOF.

os/file.go:152

func (f *File) Readdir(n int) ([]FileInfo, error)

Readdir reads the contents of the directory associated with file and returns a slice of up to n [FileInfo] values, as would be returned by [Lstat], in directory order. Subsequent calls on the same file will yield further FileInfos. If n > 0, Readdir returns at most n FileInfo structures. In this case, if Readdir returns an empty slice, it will return a non-nil error explaining why. At the end of a directory, the error is [io.EOF]. If n <= 0, Readdir returns all the FileInfo from the directo...

os/dir.go:40

func (f *File) ReadDir(n int) ([]DirEntry, error)

ReadDir reads the contents of the directory associated with the file f and returns a slice of [DirEntry] values in directory order. Subsequent calls on the same file will yield later DirEntry records in the directory. If n > 0, ReadDir returns at most n DirEntry records. In this case, if ReadDir returns an empty slice, it will return an error explaining why. At the end of a directory, the error is [io.EOF]. If n <= 0, ReadDir returns all the DirEntry records remaining in the directory. When...

os/dir.go:97

func (f *File) Readdirnames(n int) ([]string, error)

Readdirnames reads the contents of the directory associated with file and returns a slice of up to n names of files in the directory, in directory order. Subsequent calls on the same file will yield further names. If n > 0, Readdirnames returns at most n names. In this case, if Readdirnames returns an empty slice, it will return a non-nil error explaining why. At the end of a directory, the error is [io.EOF]. If n <= 0, Readdirnames returns all the names from the directory in a single slice...

os/dir.go:69

func (f *File) ReadFrom(r io.Reader) (int64, error)

ReadFrom implements io.ReaderFrom.

os/file.go:175

func (f *File) Seek(offset int64, whence int) (int64, error)

Seek sets the offset for the next Read or Write on file to offset, interpreted according to whence: 0 means relative to the origin of the file, 1 means relative to the current offset, and 2 means relative to the end. It returns the new offset and an error, if any. The behavior of Seek on a file opened with [O_APPEND] is not specified.

os/file.go:303

func (f *File) SetDeadline(t time.Time) error

SetDeadline sets the read and write deadlines for a File. It is equivalent to calling both SetReadDeadline and SetWriteDeadline. Only some kinds of files support setting a deadline. Calls to SetDeadline for files that do not support deadlines will return ErrNoDeadline. On most systems ordinary files do not support deadlines, but pipes do. A deadline is an absolute time after which I/O operations fail with an error instead of blocking. The deadline applies to all future and pending I/O, not ...

os/file.go:674

func (f *File) SetReadDeadline(t time.Time) error

SetReadDeadline sets the deadline for future Read calls and any currently-blocked Read call. A zero value for t means Read will not time out. Not all files support setting deadlines; see SetDeadline.

os/file.go:682

func (f *File) SetWriteDeadline(t time.Time) error

SetWriteDeadline sets the deadline for any future Write calls and any currently-blocked Write call. Even if Write times out, it may return n > 0, indicating that some of the data was successfully written. A zero value for t means Write will not time out. Not all files support setting deadlines; see SetDeadline.

os/file.go:692

func (f *File) Stat() (FileInfo, error)

Stat returns the [FileInfo] structure describing file. If there is an error, it will be of type [*PathError].

os/stat_unix.go:15

func (f *File) Sync() error

Sync commits the current contents of the file to stable storage. Typically, this means flushing the file system's in-memory copy of recently written data to disk.

os/file_posix.go:162

func (f *File) SyscallConn() (syscall.RawConn, error)

SyscallConn returns a raw file. This implements the syscall.Conn interface.

os/file.go:698

func (f *File) Truncate(size int64) error

Truncate changes the size of the file. It does not change the I/O offset. If there is an error, it will be of type [*PathError].

os/file_posix.go:149

func (f *File) Write(b []byte) (int, error)

Write writes len(b) bytes from b to the File. It returns the number of bytes written and an error, if any. Write returns a non-nil error when n != len(b).

os/file.go:211

func (f *File) WriteAt(b []byte, off int64) (int, error)

WriteAt writes len(b) bytes to the File starting at byte offset off. It returns the number of bytes written and an error, if any. WriteAt returns a non-nil error when n != len(b). If file was opened with the [O_APPEND] flag, WriteAt returns an error.

os/file.go:239

func (f *File) WriteString(s string) (int, error)

WriteString is like Write, but writes the contents of string s rather than a slice of bytes.

os/file.go:319

func (f *File) WriteTo(w io.Writer) (int64, error)

WriteTo implements io.WriterTo.

os/file.go:265

type FileInfo = fs.FileInfo

A FileInfo describes a file and is returned by [Stat] and [Lstat].

os/types.go:23

type FileMode = fs.FileMode

A FileMode represents a file's mode and permission bits. The bits have the same definition on all systems, so that information about files can be moved from one system to another portably. Not all bits apply to all systems. The only required bit is [ModeDir] for directories.

os/types.go:30

type LinkError struct {
	Op  string
	Old string
	New string
	Err error
}

LinkError records an error during a link or symlink or rename system call and the paths that caused it.

os/file.go:103

func (e *LinkError) Error() string

os/file.go:110

func (e *LinkError) Unwrap() error

os/file.go:114

type PathError = fs.PathError

PathError records an error and the operation and file path that caused it.

os/error.go:46

type ProcAttr struct {
	// If Dir is non-empty, the child changes into the directory before
	// creating the process.
	Dir string
	// If Env is non-nil, it gives the environment variables for the
	...

ProcAttr holds the attributes that will be applied to a new process started by StartProcess.

os/exec.go:205

type Process struct {
	Pid int
	// contains filtered or unexported fields
}

Process stores the information about a process created by [StartProcess].

os/exec.go:43

func (p *Process) Kill() error

Kill causes the [Process] to exit immediately. Kill does not wait until the Process has actually exited. This only kills the Process itself, not any other processes it may have started.

os/exec.go:336

func (p *Process) Release() error

Release releases any resources associated with the [Process] p, rendering it unusable in the future. Release only needs to be called if [Process.Wait] is not.

os/exec.go:278

func (p *Process) Signal(sig Signal) error

Signal sends a signal to the [Process]. Sending [Interrupt] on Windows is not implemented.

os/exec.go:351

func (p *Process) Wait() (*ProcessState, error)

Wait waits for the [Process] to exit, and then returns a ProcessState describing its status and an error, if any. Wait releases any resources associated with the Process. On most operating systems, the Process must be a child of the current process or an error will be returned.

os/exec.go:345

func (p *Process) WithHandle(f func(...)) error

WithHandle calls a supplied function f with a valid process handle as an argument. The handle is guaranteed to refer to process p until f returns, even if p terminates. This function cannot be used after [Process.Release] or [Process.Wait]. If process handles are not supported or a handle is not available, it returns [ErrNoHandle]. Currently, process handles are supported on Linux 5.4 or later (pidfd) and Windows.

os/exec.go:363

type ProcessState struct {
	// contains filtered or unexported fields
}

ProcessState stores information about a process, as reported by Wait.

os/exec_posix.go:98

func (p *ProcessState) ExitCode() int

ExitCode returns the exit code of the exited process, or -1 if the process hasn't exited or was terminated by a signal.

os/exec_posix.go:157

func (p *ProcessState) Exited() bool

Exited reports whether the program has exited. On Unix systems this reports true if the program exited due to calling exit, but false if the program terminated due to a signal.

os/exec.go:380

func (p *ProcessState) Pid() int

Pid returns the process id of the exited process.

os/exec_posix.go:105

func (p *ProcessState) String() string

os/exec_posix.go:125

func (p *ProcessState) Success() bool

Success reports whether the program exited successfully, such as with exit status 0 on Unix.

os/exec.go:386

func (p *ProcessState) Sys() any

Sys returns system-dependent exit information about the process. Convert it to the appropriate underlying type, such as [syscall.WaitStatus] on Unix, to access its contents.

os/exec.go:393

func (p *ProcessState) SystemTime() time.Duration

SystemTime returns the system CPU time of the exited process and its children.

os/exec.go:373

func (p *ProcessState) SysUsage() any

SysUsage returns system-dependent resource usage information about the exited process. Convert it to the appropriate underlying type, such as [*syscall.Rusage] on Unix, to access its contents. (On Unix, *syscall.Rusage matches struct rusage as defined in the getrusage(2) manual page.)

os/exec.go:402

func (p *ProcessState) UserTime() time.Duration

UserTime returns the user CPU time of the exited process and its children.

os/exec.go:368

type Root struct {
	// contains filtered or unexported fields
}

Root may be used to only access files within a single directory tree. Methods on Root can only access files and directories beneath a root directory. If any component of a file name passed to a method of Root references a location outside the root, the method returns an error. File names may reference the directory itself (.). Methods on Root will follow symbolic links, but symbolic links may not reference a location outside the root. Symbolic links must not be absolute. Methods on Root do...

os/root.go:68

func (r *Root) Chmod(name string, mode FileMode) error

Chmod changes the mode of the named file in the root to mode. See [Chmod] for more details.

os/root.go:139

func (r *Root) Chown(name string, uid int, gid int) error

Chown changes the numeric uid and gid of the named file in the root. See [Chown] for more details.

os/root.go:170

func (r *Root) Chtimes(name string, atime time.Time, mtime time.Time) error

Chtimes changes the access and modification times of the named file in the root. See [Chtimes] for more details.

os/root.go:182

func (r *Root) Close() error

Close closes the Root. After Close is called, methods on Root return errors.

os/root.go:96

func (r *Root) Create(name string) (*File, error)

Create creates or truncates the named file in the root. See [Create] for more details.

os/root.go:108

func (r *Root) FS() fs.FS

FS returns a file system (an fs.FS) for the tree of files in the root. The result implements [io/fs.StatFS], [io/fs.ReadFileFS], [io/fs.ReadDirFS], and [io/fs.ReadLinkFS].

os/root.go:357

func (r *Root) Lchown(name string, uid int, gid int) error

Lchown changes the numeric uid and gid of the named file in the root. See [Lchown] for more details.

os/root.go:176

func (r *Root) Lstat(name string) (FileInfo, error)

Lstat returns a [FileInfo] describing the named file in the root. If the file is a symbolic link, the returned FileInfo describes the symbolic link. See [Lstat] for more details.

os/root.go:209

func (r *Root) Mkdir(name string, perm FileMode) error

Mkdir creates a new directory in the root with the specified name and permission bits (before umask). See [Mkdir] for more details. If perm contains bits other than the nine least-significant bits (0o777), Mkdir returns an error.

os/root.go:149

func (r *Root) MkdirAll(name string, perm FileMode) error

MkdirAll creates a new directory in the root, along with any necessary parents. See [MkdirAll] for more details. If perm contains bits other than the nine least-significant bits (0o777), MkdirAll returns an error.

os/root.go:161

func (r *Root) Name() string

Name returns the name of the directory presented to OpenRoot. It is safe to call Name after [Close].

os/root.go:90

func (r *Root) Open(name string) (*File, error)

Open opens the named file in the root for reading. See [Open] for more details.

os/root.go:102

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

OpenFile opens the named file in the root. See [OpenFile] for more details. If perm contains bits other than the nine least-significant bits (0o777), OpenFile returns an error.

os/root.go:117

func (r *Root) OpenRoot(name string) (*Root, error)

OpenRoot opens the named directory in the root. If there is an error, it will be of type [*PathError].

os/root.go:132

func (r *Root) ReadFile(name string) ([]byte, error)

ReadFile reads the named file in the root and returns its contents. See [ReadFile] for more details.

os/root.go:253

func (r *Root) Remove(name string) error

Remove removes the named file or (empty) directory in the root. See [Remove] for more details.

os/root.go:188

func (r *Root) RemoveAll(name string) error

RemoveAll removes the named file or directory and any children that it contains. See [RemoveAll] for more details.

os/root.go:194

func (r *Root) Rename(oldname string, newname string) error

Rename renames (moves) oldname to newname. Both paths are relative to the root. See [Rename] for more details.

os/root.go:223

func (r *Root) Stat(name string) (FileInfo, error)

Stat returns a [FileInfo] describing the named file in the root. See [Stat] for more details.

os/root.go:200

func (r *Root) WriteFile(name string, data []byte, perm FileMode) error

WriteFile writes data to the named file in the root, creating it if necessary. See [WriteFile] for more details.

os/root.go:264

type Signal interface {
	String() string
	Signal() // to distinguish from other Stringers
}

A Signal represents an operating system signal. The usual underlying implementation is operating system-dependent: on Unix it is syscall.Signal.

os/exec.go:233

type SyscallError struct {
	Syscall string
	Err     error
}

SyscallError records an error from a specific system call.

os/error.go:49

func (e *SyscallError) Error() string

os/error.go:54

func (e *SyscallError) Timeout() bool

Timeout reports whether this error represents a timeout.

os/error.go:59

func (e *SyscallError) Unwrap() error

os/error.go:56