os

Package os provides a platform-independent interface to operating system functionality.

Index

Functions

func Chdir

1func 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.

func Chmod

1func 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 0200 bit (owner writable) of mode is used; it controls whether the file’s read-only attribute is set or cleared. The other bits are currently unused. For compatibility with Go 1.12 and earlier, use a non-zero mode. Use mode 0400 for a read-only file and 0600 for a readable+writable file.

On Plan 9, the mode’s permission bits, ModeAppend, ModeExclusive, and ModeTemporary are used.

1if err := os.Chmod("some-filename", 0644); err != nil {
2	log.Fatal(err)
3}

func Chown

1func Chown(name string, uid, 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 EPLAN9 error, wrapped in *PathError.

func Chtimes

1func 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.

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.

1mtime := time.Date(2006, time.February, 1, 3, 4, 5, 0, time.UTC)
2atime := time.Date(2007, time.March, 2, 4, 5, 6, 0, time.UTC)
3if err := os.Chtimes("some-filename", atime, mtime); err != nil {
4	log.Fatal(err)
5}

func Clearenv

1func Clearenv()

Clearenv deletes all environment variables.

func Environ

1func Environ() []string

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

func Exit

1func 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].

func Expand

1func Expand(s string, mapping func(string) string) 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).

 1mapper := func(placeholderName string) string {
 2	switch placeholderName {
 3	case "DAY_PART":
 4		return "morning"
 5	case "NAME":
 6		return "Gopher"
 7	}
 8
 9	return ""
10}
11
12fmt.Println(os.Expand("Good ${DAY_PART}, $NAME!", mapper))

Output

Good morning, Gopher!

func ExpandEnv

1func 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.

1os.Setenv("NAME", "gopher")
2os.Setenv("BURROW", "/usr/gopher")
3
4fmt.Println(os.ExpandEnv("$NAME lives in ${BURROW}."))

Output

gopher lives in /usr/gopher.

func Getegid

1func Getegid() int

Getegid returns the numeric effective group id of the caller.

On Windows, it returns -1.

func Getenv

1func 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.

1os.Setenv("NAME", "gopher")
2os.Setenv("BURROW", "/usr/gopher")
3
4fmt.Printf("%s lives in %s.\n", os.Getenv("NAME"), os.Getenv("BURROW"))

Output

gopher lives in /usr/gopher.

func Geteuid

1func Geteuid() int

Geteuid returns the numeric effective user id of the caller.

On Windows, it returns -1.

func Getgid

1func Getgid() int

Getgid returns the numeric group id of the caller.

On Windows, it returns -1.

func Getgroups

1func 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.

func Getpagesize

1func Getpagesize() int

Getpagesize returns the underlying system's memory page size.

func Getpid

1func Getpid() int

Getpid returns the process id of the caller.

func Getppid

1func Getppid() int

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

func Getuid

1func Getuid() int

Getuid returns the numeric user id of the caller.

On Windows, it returns -1.

func Getwd

1func Getwd() (dir string, err error)

Getwd returns a rooted 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.

func Hostname

1func Hostname() (name string, err error)

Hostname returns the host name reported by the kernel.

func IsExist

1func IsExist(err error) bool

IsExist returns a boolean indicating whether the error 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).

func IsNotExist

1func IsNotExist(err error) bool

IsNotExist returns a boolean indicating whether the error 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).

func IsPathSeparator

1func IsPathSeparator(c uint8) bool

IsPathSeparator reports whether c is a directory separator character.

func IsPermission

1func IsPermission(err error) bool

IsPermission returns a boolean indicating whether the error 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).

func Lchown

1func Lchown(name string, uid, 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.

1func Link(oldname, newname string) error

Link creates newname as a hard link to the oldname file. If there is an error, it will be of type *LinkError.

func Mkdir

1func 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.

1err := os.Mkdir("testdir", 0750)
2if err != nil && !os.IsExist(err) {
3	log.Fatal(err)
4}
5err = os.WriteFile("testdir/testfile.txt", []byte("Hello, Gophers!"), 0660)
6if err != nil {
7	log.Fatal(err)
8}

func MkdirAll

1func 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.

1err := os.MkdirAll("test/subdir", 0750)
2if err != nil && !os.IsExist(err) {
3	log.Fatal(err)
4}
5err = os.WriteFile("test/subdir/testfile.txt", []byte("Hello, Gophers!"), 0660)
6if err != nil {
7	log.Fatal(err)
8}

func NewSyscallError

1func 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.

func Pipe

1func Pipe() (r *File, w *File, err 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.

func ReadFile

1func 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.

1data, err := os.ReadFile("testdata/hello")
2if err != nil {
3	log.Fatal(err)
4}
5os.Stdout.Write(data)

Output

Hello, Gophers!
1func Readlink(name string) (string, error)

Readlink returns the destination of the named symbolic link. If there is an error, it will be of type *PathError.

func Remove

1func Remove(name string) error

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

func RemoveAll

1func 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.

func Rename

1func Rename(oldpath, newpath string) error

Rename renames (moves) oldpath to newpath. If newpath already exists and is not a directory, Rename replaces it. 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.

func SameFile

1func SameFile(fi1, 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.

func Setenv

1func Setenv(key, value string) error

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

1func Symlink(oldname, newname string) error

Symlink creates newname as a symbolic link to oldname. On Windows, a symlink to a non-existent oldname creates a file symlink; if oldname is later created as a directory the symlink will not work. If there is an error, it will be of type *LinkError.

func TempDir

1func 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.

func Truncate

1func 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.

func WriteFile

1func 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.

1err := os.WriteFile("testdata/hello", []byte("Hello, Gophers!"), 0666)
2if err != nil {
3	log.Fatal(err)
4}

func ReadDir

1func 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.

1files, err := os.ReadDir(".")
2if err != nil {
3	log.Fatal(err)
4}
5
6for _, file := range files {
7	fmt.Println(file.Name())
8}

func Create

1func 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 0666 (before umask). If successful, methods on the returned File can be used for I/O; the associated file descriptor has mode O_RDWR. If there is an error, it will be of type *PathError.

func NewFile

1func 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. On Unix systems, if the file descriptor is in non-blocking mode, NewFile will attempt to return a pollable File (one for which the SetDeadline methods work).

After passing it to NewFile, fd may become invalid under the same conditions described in the comments of the Fd method, and the same constraints apply.

func Open

1func 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.

func OpenFile

1func 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). If successful, methods on the returned File can be used for I/O. If there is an error, it will be of type *PathError.

1f, err := os.OpenFile("notes.txt", os.O_RDWR|os.O_CREATE, 0755)
2if err != nil {
3	log.Fatal(err)
4}
5if err := f.Close(); err != nil {
6	log.Fatal(err)
7}

 1f, err := os.OpenFile("access.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
 2if err != nil {
 3	log.Fatal(err)
 4}
 5if _, err := f.Write([]byte("appended some data\n")); err != nil {
 6	f.Close()
 7	log.Fatal(err)
 8}
 9if err := f.Close(); err != nil {
10	log.Fatal(err)
11}

func Lstat

1func 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.

func Stat

1func Stat(name string) (FileInfo, error)

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

func FindProcess

1func 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.

func StartProcess

1func 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. The os/exec package provides higher-level interfaces.

If there is an error, it will be of type *PathError.

Types

type Signal

1type Signal interface {
2	String() string
3	Signal()	// to distinguish from other Stringers
4}

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


© Matthias Hochgatterer – MastodonGithubRésumé