Movatterモバイル変換


[0]ホーム

URL:


os

packagestandard library
go1.25.5Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 2, 2025 License:BSD-3-ClauseImports:20Imported by:2,397,740

Details

Repository

cs.opensource.google/go/go

Links

Documentation

Overview

Package os provides a platform-independent interface to operating systemfunctionality. The design is Unix-like, although the error handling isGo-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 asOpen orStat, the errorwill include the failing file name when printed and will be of type*PathError, which may be unpacked for more information.

The os interface is intended to be uniform across all operating systems.Features not generally available appear in the system-specific package syscall.

Here is a simple example, opening a file and reading some of it.

file, err := os.Open("file.go") // For read access.if err != nil {log.Fatal(err)}

If the open fails, the error string will be self-explanatory, like

open file.go: no such file or directory

The file's data can then be read into a slice of bytes. Read andWrite take their byte counts from the length of the argument slice.

data := make([]byte, 100)count, err := file.Read(data)if err != nil {log.Fatal(err)}fmt.Printf("read %d bytes: %q\n", count, data[:count])

Concurrency

The methods ofFile correspond to file system operations. All aresafe for concurrent use. The maximum number of concurrentoperations on a File may be limited by the OS or the system. Thenumber should be high, but exceeding it may degrade performance orcause other issues.

Index

Examples

Constants

View Source
const (// Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.O_RDONLYint =syscall.O_RDONLY// open the file read-only.O_WRONLYint =syscall.O_WRONLY// open the file write-only.O_RDWRint =syscall.O_RDWR// open the file read-write.// The remaining values may be or'ed in to control behavior.O_APPENDint =syscall.O_APPEND// append data to the file when writing.O_CREATEint =syscall.O_CREAT// create a new file if none exists.O_EXCLint =syscall.O_EXCL// used with O_CREATE, file must not exist.O_SYNCint =syscall.O_SYNC// open for synchronous I/O.O_TRUNCint =syscall.O_TRUNC// truncate regular writable file when opened.)

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

View Source
const (SEEK_SETint = 0// seek relative to the origin of the fileSEEK_CURint = 1// seek relative to the current offsetSEEK_ENDint = 2// seek relative to the end)

Seek whence values.

Deprecated: Use io.SeekStart, io.SeekCurrent, and io.SeekEnd.

View Source
const (PathSeparator     = '/'// OS-specific path separatorPathListSeparator = ':'// OS-specific path list separator)
View Source
const (// The single letters are the abbreviations// used by the String method's formatting.ModeDir        =fs.ModeDir// d: is a directoryModeAppend     =fs.ModeAppend// a: append-onlyModeExclusive  =fs.ModeExclusive// l: exclusive useModeTemporary  =fs.ModeTemporary// T: temporary file; Plan 9 onlyModeSymlink    =fs.ModeSymlink// L: symbolic linkModeDevice     =fs.ModeDevice// D: device fileModeNamedPipe  =fs.ModeNamedPipe// p: named pipe (FIFO)ModeSocket     =fs.ModeSocket// S: Unix domain socketModeSetuid     =fs.ModeSetuid// u: setuidModeSetgid     =fs.ModeSetgid// g: setgidModeCharDevice =fs.ModeCharDevice// c: Unix character device, when ModeDevice is setModeSticky     =fs.ModeSticky// t: stickyModeIrregular  =fs.ModeIrregular// ?: non-regular file; nothing else is known about this file// Mask for the type bits. For regular files, none will be set.ModeType =fs.ModeTypeModePerm =fs.ModePerm// Unix permission bits, 0o777)

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

View Source
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".

Variables

View Source
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.ErrPermission// "permission denied"ErrExist      =fs.ErrExist// "file already exists"ErrNotExist   =fs.ErrNotExist// "file does not exist"ErrClosed     =fs.ErrClosed// "file already closed"ErrNoDeadline       = errNoDeadline()// "file type does not support deadline"ErrDeadlineExceeded = errDeadlineExceeded()// "i/o timeout")

Portable analogs of some common system call errors.

Errors returned from this package may be tested against these errorswitherrors.Is.

View Source
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, perhapsto a file opened later.

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

View Source
var ErrProcessDone =errors.New("os: process already finished")

ErrProcessDone indicates aProcess has finished.

Functions

funcChdir

func Chdir(dirstring)error

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

funcChmod

func Chmod(namestring, modeFileMode)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 theoperating system.

On Unix, the mode's permission bits,ModeSetuid,ModeSetgid, andModeSticky are used.

On Windows, only the 0o200 bit (owner writable) of mode is used; itcontrols whether the file's read-only attribute is set or cleared.The other bits are currently unused. For compatibility with Go 1.12and earlier, use a non-zero mode. Use mode 0o400 for a read-onlyfile and 0o600 for a readable+writable file.

On Plan 9, the mode's permission bits,ModeAppend,ModeExclusive,andModeTemporary are used.

Example
package mainimport ("log""os")func main() {if err := os.Chmod("some-filename", 0644); err != nil {log.Fatal(err)}}

funcChown

func Chown(namestring, uid, gidint)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 thesyscall.EWINDOWS orsyscall.EPLAN9 error, wrapped in*PathError.

funcChtimes

func Chtimes(namestring, atimetime.Time, mtimetime.Time)error

Chtimes changes the access and modification times of the namedfile, similar to the Unix utime() or utimes() functions.A zerotime.Time value will leave the corresponding file time unchanged.

The underlying filesystem may truncate or round the values to aless precise time unit.If there is an error, it will be of type*PathError.

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

funcClearenv

func Clearenv()

Clearenv deletes all environment variables.

funcCopyFSadded ingo1.23.0

func CopyFS(dirstring, fsysfs.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 permissionsfrom the source, and directories are created with mode 0o777(before umask).

CopyFS will not overwrite existing files. If a file name in fsysalready exists in the destination, CopyFS will return an errorsuch 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 subdirectory of fsys)while CopyFS is running are not guaranteed to be copied.

Copying stops at and returns the first error encountered.

funcDirFSadded ingo1.16

func DirFS(dirstring)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 theoperating system will begin with "/prefix": DirFS("/prefix").Open("file") is thesame as os.Open("/prefix/file"). So if /prefix/file is a symbolic link pointing outsidethe /prefix tree, then using DirFS does not stop the access any more than usingos.Open does. Additionally, the root of the fs.FS returned for a relative path,DirFS("prefix"), will be affected by later calls to Chdir. DirFS is therefore nota general substitute for a chroot-style security mechanism when the directory treecontains arbitrary content.

UseRoot.FS to obtain a fs.FS that prevents escapes from the tree via symbolic links.

The directory dir must not be "".

The result implementsio/fs.StatFS,io/fs.ReadFileFS,io/fs.ReadDirFS, andio/fs.ReadLinkFS.

funcEnviron

func Environ() []string

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

funcExecutableadded ingo1.8

func Executable() (string,error)

Executable returns the path name for the executable that startedthe current process. There is no guarantee that the path is stillpointing to the correct executable. If a symlink was used to startthe process, depending on the operating system, the result mightbe the symlink or the path it pointed to. If a stable result isneeded,path/filepath.EvalSymlinks might help.

Executable returns an absolute path unless an error occurred.

The main use case is finding resources located relative to anexecutable.

funcExit

func Exit(codeint)

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

funcExpand

func Expand(sstring, 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 toos.Expand(s,os.Getenv).

Example
package mainimport ("fmt""os")func main() {mapper := func(placeholderName string) string {switch placeholderName {case "DAY_PART":return "morning"case "NAME":return "Gopher"}return ""}fmt.Println(os.Expand("Good ${DAY_PART}, $NAME!", mapper))}
Output:Good morning, Gopher!

funcExpandEnv

func ExpandEnv(sstring)string

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

Example
package mainimport ("fmt""os")func main() {os.Setenv("NAME", "gopher")os.Setenv("BURROW", "/usr/gopher")fmt.Println(os.ExpandEnv("$NAME lives in ${BURROW}."))}
Output:gopher lives in /usr/gopher.

funcGetegid

func Getegid()int

Getegid returns the numeric effective group id of the caller.

On Windows, it returns -1.

funcGetenv

func Getenv(keystring)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, useLookupEnv.

Example
package mainimport ("fmt""os")func main() {os.Setenv("NAME", "gopher")os.Setenv("BURROW", "/usr/gopher")fmt.Printf("%s lives in %s.\n", os.Getenv("NAME"), os.Getenv("BURROW"))}
Output:gopher lives in /usr/gopher.

funcGeteuid

func Geteuid()int

Geteuid returns the numeric effective user id of the caller.

On Windows, it returns -1.

funcGetgid

func Getgid()int

Getgid returns the numeric group id of the caller.

On Windows, it returns -1.

funcGetgroups

func Getgroups() ([]int,error)

Getgroups returns a list of the numeric ids of groups that the caller belongs to.

On Windows, it returnssyscall.EWINDOWS. See theos/user packagefor a possible alternative.

funcGetpagesize

func Getpagesize()int

Getpagesize returns the underlying system's memory page size.

funcGetpid

func Getpid()int

Getpid returns the process id of the caller.

funcGetppid

func Getppid()int

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

funcGetuid

func Getuid()int

Getuid returns the numeric user id of the caller.

On Windows, it returns -1.

funcGetwd

func Getwd() (dirstring, errerror)

Getwd returns an absolute path name corresponding to thecurrent directory. If the current directory can bereached via multiple paths (due to symbolic links),Getwd may return any one of them.

On Unix platforms, if the environment variable PWDprovides an absolute name, and it is a name of thecurrent directory, it is returned.

funcHostname

func Hostname() (namestring, errerror)

Hostname returns the host name reported by the kernel.

funcIsExist

func IsExist(errerror)bool

IsExist returns a boolean indicating whether its argument is known to reportthat a file or directory already exists. It is satisfied byErrExist aswell as some syscall errors.

This function predateserrors.Is. It only supports errors returned bythe os package. New code should use errors.Is(err, fs.ErrExist).

funcIsNotExist

func IsNotExist(errerror)bool

IsNotExist returns a boolean indicating whether its argument is known toreport that a file or directory does not exist. It is satisfied byErrNotExist as well as some syscall errors.

This function predateserrors.Is. It only supports errors returned bythe os package. New code should use errors.Is(err, fs.ErrNotExist).

funcIsPathSeparator

func IsPathSeparator(cuint8)bool

IsPathSeparator reports whether c is a directory separator character.

funcIsPermission

func IsPermission(errerror)bool

IsPermission returns a boolean indicating whether its argument is known toreport that permission is denied. It is satisfied byErrPermission as wellas some syscall errors.

This function predateserrors.Is. It only supports errors returned bythe os package. New code should use errors.Is(err, fs.ErrPermission).

funcIsTimeoutadded ingo1.10

func IsTimeout(errerror)bool

IsTimeout returns a boolean indicating whether its argument is knownto report that a timeout occurred.

This function predateserrors.Is, and the notion of whether anerror indicates a timeout can be ambiguous. For example, the Unixerror EWOULDBLOCK sometimes indicates a timeout and sometimes does not.New code should use errors.Is with a value appropriate to the callreturning the error, such asos.ErrDeadlineExceeded.

funcLchown

func Lchown(namestring, uid, gidint)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 thesyscall.EWINDOWS error, wrappedin*PathError.

funcLink

func Link(oldname, newnamestring)error

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

funcLookupEnvadded ingo1.5

func LookupEnv(keystring) (string,bool)

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

Example
package mainimport ("fmt""os")func main() {show := func(key string) {val, ok := os.LookupEnv(key)if !ok {fmt.Printf("%s not set\n", key)} else {fmt.Printf("%s=%s\n", key, val)}}os.Setenv("SOME_KEY", "value")os.Setenv("EMPTY_KEY", "")show("SOME_KEY")show("EMPTY_KEY")show("MISSING_KEY")}
Output:SOME_KEY=valueEMPTY_KEY=MISSING_KEY not set

funcMkdir

func Mkdir(namestring, permFileMode)error

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

Example
package mainimport ("log""os")func main() {err := os.Mkdir("testdir", 0750)if err != nil && !os.IsExist(err) {log.Fatal(err)}err = os.WriteFile("testdir/testfile.txt", []byte("Hello, Gophers!"), 0660)if err != nil {log.Fatal(err)}}

funcMkdirAll

func MkdirAll(pathstring, permFileMode)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 alldirectories that MkdirAll creates.If path is already a directory, MkdirAll does nothingand returns nil.

Example
package mainimport ("log""os")func main() {err := os.MkdirAll("test/subdir", 0750)if err != nil {log.Fatal(err)}err = os.WriteFile("test/subdir/testfile.txt", []byte("Hello, Gophers!"), 0660)if err != nil {log.Fatal(err)}}

funcMkdirTempadded ingo1.16

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

MkdirTemp creates a new temporary directory in the directory dirand 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 simultaneously will not choose the same directory.It is the caller's responsibility to remove the directory when it is no longer needed.

Example
package mainimport ("log""os""path/filepath")func main() {dir, err := os.MkdirTemp("", "example")if err != nil {log.Fatal(err)}defer os.RemoveAll(dir) // clean upfile := filepath.Join(dir, "tmpfile")if err := os.WriteFile(file, []byte("content"), 0666); err != nil {log.Fatal(err)}}

Example (Suffix)
package mainimport ("log""os""path/filepath")func main() {logsDir, err := os.MkdirTemp("", "*-logs")if err != nil {log.Fatal(err)}defer os.RemoveAll(logsDir) // clean up// Logs can be cleaned out earlier if needed by searching// for all directories whose suffix ends in *-logs.globPattern := filepath.Join(os.TempDir(), "*-logs")matches, err := filepath.Glob(globPattern)if err != nil {log.Fatalf("Failed to match %q: %v", globPattern, err)}for _, match := range matches {if err := os.RemoveAll(match); err != nil {log.Printf("Failed to remove %q: %v", match, err)}}}

funcNewSyscallError

func NewSyscallError(syscallstring, errerror)error

NewSyscallError returns, as an error, a newSyscallErrorwith the given system call name and error details.As a convenience, if err is nil, NewSyscallError returns nil.

funcPipe

func Pipe() (r *File, w *File, errerror)

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

funcReadFileadded ingo1.16

func ReadFile(namestring) ([]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 Readas an error to be reported.

Example
package mainimport ("log""os")func main() {data, err := os.ReadFile("testdata/hello")if err != nil {log.Fatal(err)}os.Stdout.Write(data)}
Output:Hello, Gophers!

funcReadlink

func Readlink(namestring) (string,error)

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

If the link destination is relative, Readlink returns the relative pathwithout resolving it to an absolute one.

Example
package mainimport ("errors""fmt""log""os""path/filepath")func main() {// First, we create a relative symlink to a file.d, err := os.MkdirTemp("", "")if err != nil {log.Fatal(err)}defer os.RemoveAll(d)targetPath := filepath.Join(d, "hello.txt")if err := os.WriteFile(targetPath, []byte("Hello, Gophers!"), 0644); err != nil {log.Fatal(err)}linkPath := filepath.Join(d, "hello.link")if err := os.Symlink("hello.txt", filepath.Join(d, "hello.link")); err != nil {if errors.Is(err, errors.ErrUnsupported) {// Allow the example to run on platforms that do not support symbolic links.fmt.Printf("%s links to %s\n", filepath.Base(linkPath), "hello.txt")return}log.Fatal(err)}// Readlink returns the relative path as passed to os.Symlink.dst, err := os.Readlink(linkPath)if err != nil {log.Fatal(err)}fmt.Printf("%s links to %s\n", filepath.Base(linkPath), dst)var dstAbs stringif filepath.IsAbs(dst) {dstAbs = dst} else {// Symlink targets are relative to the directory containing the link.dstAbs = filepath.Join(filepath.Dir(linkPath), dst)}// Check that the target is correct by comparing it with os.Stat// on the original target path.dstInfo, err := os.Stat(dstAbs)if err != nil {log.Fatal(err)}targetInfo, err := os.Stat(targetPath)if err != nil {log.Fatal(err)}if !os.SameFile(dstInfo, targetInfo) {log.Fatalf("link destination (%s) is not the same file as %s", dstAbs, targetPath)}}
Output:hello.link links to hello.txt

funcRemove

func Remove(namestring)error

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

funcRemoveAll

func RemoveAll(pathstring)error

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

funcRename

func Rename(oldpath, newpathstring)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.

funcSameFile

func SameFile(fi1, fi2FileInfo)bool

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

funcSetenv

func Setenv(key, valuestring)error

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

funcSymlink

func Symlink(oldname, newnamestring)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.

funcTempDir

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-emptyvalue from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory.On Plan 9, it returns /tmp.

The directory is neither guaranteed to exist nor have accessiblepermissions.

funcTruncate

func Truncate(namestring, sizeint64)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.

funcUnsetenvadded ingo1.4

func Unsetenv(keystring)error

Unsetenv unsets a single environment variable.

Example
package mainimport ("os")func main() {os.Setenv("TMPDIR", "/my/tmp")defer os.Unsetenv("TMPDIR")}

funcUserCacheDiradded ingo1.11

func UserCacheDir() (string,error)

UserCacheDir returns the default root directory to use for user-specificcached data. Users should create their own application-specific subdirectorywithin this one and use that.

On Unix systems, it returns $XDG_CACHE_HOME as specified byhttps://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html ifnon-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 be determined (for example, $HOME is not defined) orthe path in $XDG_CACHE_HOME is relative, then it will return an error.

Example
package mainimport ("log""os""path/filepath""sync")func main() {dir, dirErr := os.UserCacheDir()if dirErr == nil {dir = filepath.Join(dir, "ExampleUserCacheDir")}getCache := func(name string) ([]byte, error) {if dirErr != nil {return nil, &os.PathError{Op: "getCache", Path: name, Err: os.ErrNotExist}}return os.ReadFile(filepath.Join(dir, name))}var mkdirOnce sync.OnceputCache := func(name string, b []byte) error {if dirErr != nil {return &os.PathError{Op: "putCache", Path: name, Err: dirErr}}mkdirOnce.Do(func() {if err := os.MkdirAll(dir, 0700); err != nil {log.Printf("can't create user cache dir: %v", err)}})return os.WriteFile(filepath.Join(dir, name), b, 0600)}// Read and store cached data.// …_ = getCache_ = putCache}

funcUserConfigDiradded ingo1.13

func UserConfigDir() (string,error)

UserConfigDir returns the default root directory to use for user-specificconfiguration data. Users should create their own application-specificsubdirectory within this one and use that.

On Unix systems, it returns $XDG_CONFIG_HOME as specified byhttps://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html ifnon-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 location cannot be determined (for example, $HOME is not defined) orthe path in $XDG_CONFIG_HOME is relative, then it will return an error.

Example
package mainimport ("bytes""log""os""path/filepath")func main() {dir, dirErr := os.UserConfigDir()var (configPath stringorigConfig []byte)if dirErr == nil {configPath = filepath.Join(dir, "ExampleUserConfigDir", "example.conf")var err errororigConfig, err = os.ReadFile(configPath)if err != nil && !os.IsNotExist(err) {// The user has a config file but we couldn't read it.// Report the error instead of ignoring their configuration.log.Fatal(err)}}// Use and perhaps make changes to the config.config := bytes.Clone(origConfig)// …// Save changes.if !bytes.Equal(config, origConfig) {if configPath == "" {log.Printf("not saving config changes: %v", dirErr)} else {err := os.MkdirAll(filepath.Dir(configPath), 0700)if err == nil {err = os.WriteFile(configPath, config, 0600)}if err != nil {log.Printf("error saving config changes: %v", err)}}}}

funcUserHomeDiradded ingo1.12

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, UserHomeDirreturns either a platform-specific default value or a non-nil error.

funcWriteFileadded ingo1.16

func WriteFile(namestring, data []byte, permFileMode)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-operationcan leave the file in a partially written state.

Example
package mainimport ("log""os")func main() {err := os.WriteFile("testdata/hello", []byte("Hello, Gophers!"), 0666)if err != nil {log.Fatal(err)}}

Types

typeDirEntryadded ingo1.16

type DirEntry =fs.DirEntry

A DirEntry is an entry read from a directory(using theReadDir function or aFile.ReadDir method).

funcReadDiradded ingo1.16

func ReadDir(namestring) ([]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.

Example
package mainimport ("fmt""log""os")func main() {files, err := os.ReadDir(".")if err != nil {log.Fatal(err)}for _, file := range files {fmt.Println(file.Name())}}

typeFile

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

File represents an open file descriptor.

The methods of File are safe for concurrent use.

funcCreate

func Create(namestring) (*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 canbe used for I/O; the associated file descriptor has modeO_RDWR.The directory containing the file must already exist.If there is an error, it will be of type*PathError.

funcCreateTempadded ingo1.16

func CreateTemp(dir, patternstring) (*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 byTempDir.Multiple programs or goroutines calling CreateTemp simultaneously will not choose the same file.The caller can use the file's Name method to find the pathname of the file.It is the caller's responsibility to remove the file when it is no longer needed.

Example
package mainimport ("log""os")func main() {f, err := os.CreateTemp("", "example")if err != nil {log.Fatal(err)}defer os.Remove(f.Name()) // clean upif _, err := f.Write([]byte("content")); err != nil {log.Fatal(err)}if err := f.Close(); err != nil {log.Fatal(err)}}

Example (Suffix)
package mainimport ("log""os")func main() {f, err := os.CreateTemp("", "example.*.txt")if err != nil {log.Fatal(err)}defer os.Remove(f.Name()) // clean upif _, err := f.Write([]byte("content")); err != nil {f.Close()log.Fatal(err)}if err := f.Close(); err != nil {log.Fatal(err)}}

funcNewFile

func NewFile(fduintptr, namestring) *File

NewFile returns a newFile 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_OVERLAPPEDhas been specified in thesyscall.CreateFile call), NewFile will attempt to return a pollablefile by associating fd with the Go runtime I/O completion port.The I/O operations will be performed synchronously if the association fails.

Only pollable files supportFile.SetDeadline,File.SetReadDeadline, andFile.SetWriteDeadline.

After passing it to NewFile, fd may become invalid under the same conditions describedin the comments ofFile.Fd, and the same constraints apply.

funcOpen

func Open(namestring) (*File,error)

Open opens the named file for reading. If successful, methods onthe returned file can be used for reading; the associated filedescriptor has modeO_RDONLY.If there is an error, it will be of type*PathError.

funcOpenFile

func OpenFile(namestring, flagint, permFileMode) (*File,error)

OpenFile is the generalized open call; most users will use Openor Create instead. It opens the named file with specified flag(O_RDONLY etc.). If the file does not exist, and theO_CREATE flagis 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.

Example
package mainimport ("log""os")func main() {f, err := os.OpenFile("notes.txt", os.O_RDWR|os.O_CREATE, 0644)if err != nil {log.Fatal(err)}if err := f.Close(); err != nil {log.Fatal(err)}}

Example (Append)
package mainimport ("log""os")func main() {// If the file doesn't exist, create it, or append to the filef, err := os.OpenFile("access.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)if err != nil {log.Fatal(err)}if _, err := f.Write([]byte("appended some data\n")); err != nil {f.Close() // ignore error; Write error takes precedencelog.Fatal(err)}if err := f.Close(); err != nil {log.Fatal(err)}}

funcOpenInRootadded ingo1.24.0

func OpenInRoot(dir, namestring) (*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 namereferences a location outside of dir.

SeeRoot for details and limitations.

func (*File)Chdir

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.

func (*File)Chmod

func (f *File) Chmod(modeFileMode)error

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

func (*File)Chown

func (f *File) Chown(uid, gidint)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 thesyscall.EWINDOWS error, wrappedin*PathError.

func (*File)Close

func (f *File) Close()error

Close closes theFile, rendering it unusable for I/O.On files that supportFile.SetDeadline, any pending I/O operations willbe canceled and return immediately with anErrClosed error.Close will return an error if it has already been called.

func (*File)Fd

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; seeruntime.SetFinalizer for more information on whena finalizer might be run.

Do not close the returned descriptor; that could cause a laterclose of f to close an unrelated descriptor.

Fd's behavior differs on some platforms:

  • On Unix and Windows,File.SetDeadline methods will stop working.
  • On Windows, the file descriptor will be disassociated from theGo runtime I/O completion port if there are no concurrent I/Ooperations on the file.

For most uses prefer the f.SyscallConn method.

func (*File)Name

func (f *File) Name()string

Name returns the name of the file as presented to Open.

It is safe to call Name after [Close].

func (*File)Read

func (f *File) Read(b []byte) (nint, errerror)

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.

func (*File)ReadAt

func (f *File) ReadAt(b []byte, offint64) (nint, errerror)

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.

func (*File)ReadDiradded ingo1.16

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

ReadDir reads the contents of the directory associated with the file fand returns a slice ofDirEntry 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 isio.EOF.

If n <= 0, ReadDir returns all the DirEntry records remaining in the directory.When it succeeds, it returns a nil error (not io.EOF).

func (*File)ReadFromadded ingo1.15

func (f *File) ReadFrom(rio.Reader) (nint64, errerror)

ReadFrom implements io.ReaderFrom.

func (*File)Readdir

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

Readdir reads the contents of the directory associated with file andreturns a slice of up to nFileInfo values, as would be returnedbyLstat, in directory order. Subsequent calls on the same file will yieldfurther FileInfos.

If n > 0, Readdir returns at most n FileInfo structures. In this case, ifReaddir returns an empty slice, it will return a non-nil errorexplaining why. At the end of a directory, the error isio.EOF.

If n <= 0, Readdir returns all the FileInfo from the directory ina single slice. In this case, if Readdir succeeds (reads allthe way to the end of the directory), it returns the slice and anil error. If it encounters an error before the end of thedirectory, Readdir returns the FileInfo read until that pointand a non-nil error.

Most clients are better served by the more efficient ReadDir method.

func (*File)Readdirnames

func (f *File) Readdirnames(nint) (names []string, errerror)

Readdirnames reads the contents of the directory associated with fileand returns a slice of up to n names of files in the directory,in directory order. Subsequent calls on the same file will yieldfurther names.

If n > 0, Readdirnames returns at most n names. In this case, ifReaddirnames returns an empty slice, it will return a non-nil errorexplaining why. At the end of a directory, the error isio.EOF.

If n <= 0, Readdirnames returns all the names from the directory ina single slice. In this case, if Readdirnames succeeds (reads allthe way to the end of the directory), it returns the slice and anil error. If it encounters an error before the end of thedirectory, Readdirnames returns the names read until that point anda non-nil error.

func (*File)Seek

func (f *File) Seek(offsetint64, whenceint) (retint64, errerror)

Seek sets the offset for the next Read or Write on file to offset, interpretedaccording to whence: 0 means relative to the origin of the file, 1 meansrelative 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 withO_APPEND is not specified.

func (*File)SetDeadlineadded ingo1.10

func (f *File) SetDeadline(ttime.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 SetDeadlinefor 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 anerror instead of blocking. The deadline applies to all future and pendingI/O, not just the immediately following call to Read or Write.After a deadline has been exceeded, the connection can be refreshedby setting a deadline in the future.

If the deadline is exceeded a call to Read or Write or to other I/Omethods will return an error that wraps ErrDeadlineExceeded.This can be tested using errors.Is(err, os.ErrDeadlineExceeded).That error implements the Timeout method, and calling the Timeoutmethod will return true, but there are other possible errors for whichthe Timeout will return true even if the deadline has not been exceeded.

An idle timeout can be implemented by repeatedly extendingthe deadline after successful Read or Write calls.

A zero value for t means I/O operations will not time out.

func (*File)SetReadDeadlineadded ingo1.10

func (f *File) SetReadDeadline(ttime.Time)error

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

func (*File)SetWriteDeadlineadded ingo1.10

func (f *File) SetWriteDeadline(ttime.Time)error

SetWriteDeadline sets the deadline for any future Write calls and anycurrently-blocked Write call.Even if Write times out, it may return n > 0, indicating thatsome 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.

func (*File)Stat

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

Stat returns theFileInfo structure describing file.If there is an error, it will be of type*PathError.

func (*File)Sync

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 copyof recently written data to disk.

func (*File)SyscallConnadded ingo1.12

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

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

func (*File)Truncate

func (f *File) Truncate(sizeint64)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.

func (*File)Write

func (f *File) Write(b []byte) (nint, errerror)

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).

func (*File)WriteAt

func (f *File) WriteAt(b []byte, offint64) (nint, errerror)

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 theO_APPEND flag, WriteAt returns an error.

func (*File)WriteString

func (f *File) WriteString(sstring) (nint, errerror)

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

func (*File)WriteToadded ingo1.22.0

func (f *File) WriteTo(wio.Writer) (nint64, errerror)

WriteTo implements io.WriterTo.

typeFileInfo

type FileInfo =fs.FileInfo

A FileInfo describes a file and is returned byStat andLstat.

funcLstat

func Lstat(namestring) (FileInfo,error)

Lstat returns aFileInfo describing the named file.If the file is a symbolic link, the returned FileInfodescribes 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 anothernamed entity (such as a symbolic link or mounted folder), the returnedFileInfo describes the reparse point, and makes no attempt to resolve it.

funcStat

func Stat(namestring) (FileInfo,error)

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

typeFileMode

type FileMode =fs.FileMode

A FileMode represents a file's mode and permission bits.The bits have the same definition on all systems, so thatinformation about files can be moved from one systemto another portably. Not all bits apply to all systems.The only required bit isModeDir for directories.

Example
package mainimport ("fmt""io/fs""log""os")func main() {fi, err := os.Lstat("some-filename")if err != nil {log.Fatal(err)}fmt.Printf("permissions: %#o\n", fi.Mode().Perm()) // 0o400, 0o777, etc.switch mode := fi.Mode(); {case mode.IsRegular():fmt.Println("regular file")case mode.IsDir():fmt.Println("directory")case mode&fs.ModeSymlink != 0:fmt.Println("symbolic link")case mode&fs.ModeNamedPipe != 0:fmt.Println("named pipe")}}

typeLinkError

type LinkError struct {OpstringOldstringNewstringErrerror}

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

func (*LinkError)Error

func (e *LinkError) Error()string

func (*LinkError)Unwrapadded ingo1.13

func (e *LinkError) Unwrap()error

typePathError

type PathError =fs.PathError

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

typeProcAttr

type ProcAttr struct {// If Dir is non-empty, the child changes into the directory before// creating the process.Dirstring// If Env is non-nil, it gives the environment variables for the// new process in the form returned by Environ.// If it is nil, the result of Environ will be used.Env []string// Files specifies the open files inherited by the new process. The// first three entries correspond to standard input, standard output, and// standard error. An implementation may support additional entries,// depending on the underlying operating system. A nil entry corresponds// to that file being closed when the process starts.// On Unix systems, StartProcess will change these File values// to blocking mode, which means that SetDeadline will stop working// and calling Close will not interrupt a Read or Write.Files []*File// Operating system-specific process creation attributes.// Note that setting this field means that your program// may not execute properly or even compile on some// operating systems.Sys *syscall.SysProcAttr}

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

typeProcess

type Process struct {Pidint// contains filtered or unexported fields}

Process stores the information about a process created byStartProcess.

funcFindProcess

func FindProcess(pidint) (*Process,error)

FindProcess looks for a running process by its pid.

TheProcess it returns can be used to obtain informationabout the underlying operating system process.

On Unix systems, FindProcess always succeeds and returns a Processfor the given pid, regardless of whether the process exists. To test whetherthe process actually exists, see whether p.Signal(syscall.Signal(0)) reportsan error.

funcStartProcess

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

StartProcess starts a new process with the program, arguments and attributesspecified by name, argv and attr. The argv slice will becomeos.Args in thenew process, so it normally starts with the program name.

If the calling goroutine has locked the operating system threadwithruntime.LockOSThread and modified any inheritable OS-levelthread state (for example, Linux or Plan 9 name spaces), the newprocess will inherit the caller's thread state.

StartProcess is a low-level interface. Theos/exec package provideshigher-level interfaces.

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

func (*Process)Kill

func (p *Process) Kill()error

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

func (*Process)Release

func (p *Process) Release()error

Release releases any resources associated with theProcess p,rendering it unusable in the future.Release only needs to be called ifProcess.Wait is not.

func (*Process)Signal

func (p *Process) Signal(sigSignal)error

Signal sends a signal to theProcess.SendingInterrupt on Windows is not implemented.

func (*Process)Wait

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

Wait waits for theProcess to exit, and then returns aProcessState 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 childof the current process or an error will be returned.

typeProcessState

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

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

func (*ProcessState)ExitCodeadded ingo1.12

func (p *ProcessState) ExitCode()int

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

func (*ProcessState)Exited

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.

func (*ProcessState)Pid

func (p *ProcessState) Pid()int

Pid returns the process id of the exited process.

func (*ProcessState)String

func (p *ProcessState) String()string

func (*ProcessState)Success

func (p *ProcessState) Success()bool

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

func (*ProcessState)Sys

func (p *ProcessState) Sys()any

Sys returns system-dependent exit information aboutthe process. Convert it to the appropriate underlyingtype, such assyscall.WaitStatus on Unix, to access its contents.

func (*ProcessState)SysUsage

func (p *ProcessState) SysUsage()any

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

func (*ProcessState)SystemTime

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

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

func (*ProcessState)UserTime

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

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

typeRootadded ingo1.24.0

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 locationoutside 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 notreference a location outside the root.Symbolic links must not be absolute.

Methods on Root do not prohibit traversal of filesystem boundaries,Linux bind mounts, /proc special files, or access to Unix device files.

Methods on Root are safe to be used from multiple goroutines simultaneously.

On most platforms, creating a Root opens a file descriptor or handle referencingthe directory. If the directory is moved, methods on Root reference the originaldirectory in its new location.

Root's behavior differs on some platforms:

  • When GOOS=windows, file names may not reference Windows reserved device namessuch as NUL and COM1.
  • On Unix,Root.Chmod,Root.Chown, andRoot.Chtimes are vulnerable to a race condition.If the target of the operation is changed from a regular file to a symlinkwhile the operation is in progress, the operation may be performed on the linkrather than the link target.
  • When GOOS=js, Root is vulnerable to TOCTOU (time-of-check-time-of-use)attacks in symlink validation, and cannot ensure that operations will notescape the root.
  • When GOOS=plan9 or GOOS=js, Root does not track directories across renames.On these platforms, a Root references a directory name, not a file descriptor.
  • WASI preview 1 (GOOS=wasip1) does not supportRoot.Chmod.

funcOpenRootadded ingo1.24.0

func OpenRoot(namestring) (*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.

func (*Root)Chmodadded ingo1.25.0

func (r *Root) Chmod(namestring, modeFileMode)error

Chmod changes the mode of the named file in the root to mode.SeeChmod for more details.

func (*Root)Chownadded ingo1.25.0

func (r *Root) Chown(namestring, uid, gidint)error

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

func (*Root)Chtimesadded ingo1.25.0

func (r *Root) Chtimes(namestring, atimetime.Time, mtimetime.Time)error

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

func (*Root)Closeadded ingo1.24.0

func (r *Root) Close()error

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

func (*Root)Createadded ingo1.24.0

func (r *Root) Create(namestring) (*File,error)

Create creates or truncates the named file in the root.SeeCreate for more details.

func (*Root)FSadded ingo1.24.0

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

FS returns a file system (an fs.FS) for the tree of files in the root.

The result implementsio/fs.StatFS,io/fs.ReadFileFS,io/fs.ReadDirFS, andio/fs.ReadLinkFS.

func (*Root)Lchownadded ingo1.25.0

func (r *Root) Lchown(namestring, uid, gidint)error

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

func (*Root)Linkadded ingo1.25.0

func (r *Root) Link(oldname, newnamestring)error

Link creates newname as a hard link to the oldname file.Both paths are relative to the root.SeeLink for more details.

If oldname is a symbolic link, Link creates new link to oldname and not its target.This behavior may differ from that ofLink on some platforms.

When GOOS=js, Link returns an error if oldname is a symbolic link.

func (*Root)Lstatadded ingo1.24.0

func (r *Root) Lstat(namestring) (FileInfo,error)

Lstat returns aFileInfo describing the named file in the root.If the file is a symbolic link, the returned FileInfodescribes the symbolic link.SeeLstat for more details.

func (*Root)Mkdiradded ingo1.24.0

func (r *Root) Mkdir(namestring, permFileMode)error

Mkdir creates a new directory in the rootwith the specified name and permission bits (before umask).SeeMkdir for more details.

If perm contains bits other than the nine least-significant bits (0o777),Mkdir returns an error.

func (*Root)MkdirAlladded ingo1.25.0

func (r *Root) MkdirAll(namestring, permFileMode)error

MkdirAll creates a new directory in the root, along with any necessary parents.SeeMkdirAll for more details.

If perm contains bits other than the nine least-significant bits (0o777),MkdirAll returns an error.

func (*Root)Nameadded ingo1.24.0

func (r *Root) Name()string

Name returns the name of the directory presented to OpenRoot.

It is safe to call Name after [Close].

func (*Root)Openadded ingo1.24.0

func (r *Root) Open(namestring) (*File,error)

Open opens the named file in the root for reading.SeeOpen for more details.

func (*Root)OpenFileadded ingo1.24.0

func (r *Root) OpenFile(namestring, flagint, permFileMode) (*File,error)

OpenFile opens the named file in the root.SeeOpenFile for more details.

If perm contains bits other than the nine least-significant bits (0o777),OpenFile returns an error.

func (*Root)OpenRootadded ingo1.24.0

func (r *Root) OpenRoot(namestring) (*Root,error)

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

func (*Root)ReadFileadded ingo1.25.0

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

ReadFile reads the named file in the root and returns its contents.SeeReadFile for more details.

func (*Root)Readlinkadded ingo1.25.0

func (r *Root) Readlink(namestring) (string,error)

Readlink returns the destination of the named symbolic link in the root.SeeReadlink for more details.

func (*Root)Removeadded ingo1.24.0

func (r *Root) Remove(namestring)error

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

func (*Root)RemoveAlladded ingo1.25.0

func (r *Root) RemoveAll(namestring)error

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

func (*Root)Renameadded ingo1.25.0

func (r *Root) Rename(oldname, newnamestring)error

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

func (*Root)Statadded ingo1.24.0

func (r *Root) Stat(namestring) (FileInfo,error)

Stat returns aFileInfo describing the named file in the root.SeeStat for more details.

func (*Root)Symlinkadded ingo1.25.0

func (r *Root) Symlink(oldname, newnamestring)error

Symlink creates newname as a symbolic link to oldname.SeeSymlink for more details.

Symlink does not validate oldname,which may reference a location outside the root.

On Windows, a directory link is created if oldname referencesa directory within the root. Otherwise a file link is created.

func (*Root)WriteFileadded ingo1.25.0

func (r *Root) WriteFile(namestring, data []byte, permFileMode)error

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

typeSignal

type Signal interface {String()stringSignal()// 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.

The only signal values guaranteed to be present in the os package on allsystems are os.Interrupt (send the process an interrupt) and os.Kill (forcethe process to exit). On Windows, sending os.Interrupt to a process withos.Process.Signal is not implemented; it will return an error instead ofsending a signal.

typeSyscallError

type SyscallError struct {SyscallstringErrerror}

SyscallError records an error from a specific system call.

func (*SyscallError)Error

func (e *SyscallError) Error()string

func (*SyscallError)Timeoutadded ingo1.10

func (e *SyscallError) Timeout()bool

Timeout reports whether this error represents a timeout.

func (*SyscallError)Unwrapadded ingo1.13

func (e *SyscallError) Unwrap()error

Source Files

View all Source files

Directories

PathSynopsis
Package exec runs external commands.
Package exec runs external commands.
internal/fdtest
Package fdtest provides test helpers for working with file descriptors across exec.
Package fdtest provides test helpers for working with file descriptors across exec.
Package signal implements access to incoming signals.
Package signal implements access to incoming signals.
Package user allows user account lookups by name or id.
Package user allows user account lookups by name or id.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp