os
packagestandard libraryThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
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¶
- Constants
- Variables
- func Chdir(dir string) error
- func Chmod(name string, mode FileMode) error
- func Chown(name string, uid, gid int) error
- func Chtimes(name string, atime time.Time, mtime time.Time) error
- func Clearenv()
- func CopyFS(dir string, fsys fs.FS) error
- func DirFS(dir string) fs.FS
- func Environ() []string
- func Executable() (string, error)
- func Exit(code int)
- func Expand(s string, mapping func(string) string) string
- func ExpandEnv(s string) string
- func Getegid() int
- func Getenv(key string) string
- func Geteuid() int
- func Getgid() int
- func Getgroups() ([]int, error)
- func Getpagesize() int
- func Getpid() int
- func Getppid() int
- func Getuid() int
- func Getwd() (dir string, err error)
- func Hostname() (name string, err error)
- func IsExist(err error) bool
- func IsNotExist(err error) bool
- func IsPathSeparator(c uint8) bool
- func IsPermission(err error) bool
- func IsTimeout(err error) bool
- func Lchown(name string, uid, gid int) error
- func Link(oldname, newname string) error
- func LookupEnv(key string) (string, bool)
- func Mkdir(name string, perm FileMode) error
- func MkdirAll(path string, perm FileMode) error
- func MkdirTemp(dir, pattern string) (string, error)
- func NewSyscallError(syscall string, err error) error
- func Pipe() (r *File, w *File, err error)
- func ReadFile(name string) ([]byte, error)
- func Readlink(name string) (string, error)
- func Remove(name string) error
- func RemoveAll(path string) error
- func Rename(oldpath, newpath string) error
- func SameFile(fi1, fi2 FileInfo) bool
- func Setenv(key, value string) error
- func Symlink(oldname, newname string) error
- func TempDir() string
- func Truncate(name string, size int64) error
- func Unsetenv(key string) error
- func UserCacheDir() (string, error)
- func UserConfigDir() (string, error)
- func UserHomeDir() (string, error)
- func WriteFile(name string, data []byte, perm FileMode) error
- type DirEntry
- type File
- func (f *File) Chdir() error
- func (f *File) Chmod(mode FileMode) error
- func (f *File) Chown(uid, gid int) error
- func (f *File) Close() error
- func (f *File) Fd() uintptr
- func (f *File) Name() string
- func (f *File) Read(b []byte) (n int, err error)
- func (f *File) ReadAt(b []byte, off int64) (n int, err error)
- func (f *File) ReadDir(n int) ([]DirEntry, error)
- func (f *File) ReadFrom(r io.Reader) (n int64, err error)
- func (f *File) Readdir(n int) ([]FileInfo, error)
- func (f *File) Readdirnames(n int) (names []string, err error)
- func (f *File) Seek(offset int64, whence int) (ret int64, err error)
- func (f *File) SetDeadline(t time.Time) error
- func (f *File) SetReadDeadline(t time.Time) error
- func (f *File) SetWriteDeadline(t time.Time) error
- func (f *File) Stat() (FileInfo, error)
- func (f *File) Sync() error
- func (f *File) SyscallConn() (syscall.RawConn, error)
- func (f *File) Truncate(size int64) error
- func (f *File) Write(b []byte) (n int, err error)
- func (f *File) WriteAt(b []byte, off int64) (n int, err error)
- func (f *File) WriteString(s string) (n int, err error)
- func (f *File) WriteTo(w io.Writer) (n int64, err error)
- type FileInfo
- type FileMode
- type LinkError
- type PathError
- type ProcAttr
- type Process
- type ProcessState
- func (p *ProcessState) ExitCode() int
- func (p *ProcessState) Exited() bool
- func (p *ProcessState) Pid() int
- func (p *ProcessState) String() string
- func (p *ProcessState) Success() bool
- func (p *ProcessState) Sys() any
- func (p *ProcessState) SysUsage() any
- func (p *ProcessState) SystemTime() time.Duration
- func (p *ProcessState) UserTime() time.Duration
- type Root
- func (r *Root) Chmod(name string, mode FileMode) error
- func (r *Root) Chown(name string, uid, gid int) error
- func (r *Root) Chtimes(name string, atime time.Time, mtime time.Time) error
- func (r *Root) Close() error
- func (r *Root) Create(name string) (*File, error)
- func (r *Root) FS() fs.FS
- func (r *Root) Lchown(name string, uid, gid int) error
- func (r *Root) Link(oldname, newname string) error
- func (r *Root) Lstat(name string) (FileInfo, error)
- func (r *Root) Mkdir(name string, perm FileMode) error
- func (r *Root) MkdirAll(name string, perm FileMode) error
- func (r *Root) Name() string
- func (r *Root) Open(name string) (*File, error)
- func (r *Root) OpenFile(name string, flag int, perm FileMode) (*File, error)
- func (r *Root) OpenRoot(name string) (*Root, error)
- func (r *Root) ReadFile(name string) ([]byte, error)
- func (r *Root) Readlink(name string) (string, error)
- func (r *Root) Remove(name string) error
- func (r *Root) RemoveAll(name string) error
- func (r *Root) Rename(oldname, newname string) error
- func (r *Root) Stat(name string) (FileInfo, error)
- func (r *Root) Symlink(oldname, newname string) error
- func (r *Root) WriteFile(name string, data []byte, perm FileMode) error
- type Signal
- type SyscallError
Examples¶
Constants¶
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.
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.
const (PathSeparator = '/'// OS-specific path separatorPathListSeparator = ':'// OS-specific path list separator)
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.
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¶
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.
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.
var Args []stringArgs hold the command-line arguments, starting with the program name.
var ErrProcessDone =errors.New("os: process already finished")ErrProcessDone indicates aProcess has finished.
Functions¶
funcChdir¶
Chdir changes the current working directory to the named directory.If there is an error, it will be of type*PathError.
funcChmod¶
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¶
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¶
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)}}funcCopyFS¶added ingo1.23.0
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.
funcDirFS¶added ingo1.16
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".
funcExecutable¶added ingo1.8
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¶
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¶
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¶
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¶
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.
funcGetuid¶
func Getuid()int
Getuid returns the numeric user id of the caller.
On Windows, it returns -1.
funcGetwd¶
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.
funcIsExist¶
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¶
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¶
IsPathSeparator reports whether c is a directory separator character.
funcIsPermission¶
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).
funcIsTimeout¶added ingo1.10
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¶
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¶
Link creates newname as a hard link to the oldname file.If there is an error, it will be of type *LinkError.
funcLookupEnv¶added ingo1.5
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¶
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¶
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)}}funcMkdirTemp¶added ingo1.16
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¶
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¶
Pipe returns a connected pair of Files; reads from r return bytes written to w.It returns the files and an error, if any.
funcReadFile¶added ingo1.16
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¶
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¶
Remove removes the named file or (empty) directory.If there is an error, it will be of type*PathError.
funcRemoveAll¶
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¶
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¶
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¶
Setenv sets the value of the environment variable named by the key.It returns an error, if any.
funcSymlink¶
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¶
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.
funcUnsetenv¶added ingo1.4
Unsetenv unsets a single environment variable.
Example¶
package mainimport ("os")func main() {os.Setenv("TMPDIR", "/my/tmp")defer os.Unsetenv("TMPDIR")}funcUserCacheDir¶added ingo1.11
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}funcUserConfigDir¶added ingo1.13
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)}}}}funcUserHomeDir¶added ingo1.12
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.
funcWriteFile¶added ingo1.16
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¶
typeDirEntry¶added ingo1.16
A DirEntry is an entry read from a directory(using theReadDir function or aFile.ReadDir method).
funcReadDir¶added ingo1.16
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¶
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.
funcCreateTemp¶added ingo1.16
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¶
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¶
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¶
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)}}funcOpenInRoot¶added ingo1.24.0
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¶
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¶
Chmod changes the mode of the file to mode.If there is an error, it will be of type*PathError.
func (*File)Chown¶
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¶
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¶
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¶
Name returns the name of the file as presented to Open.
It is safe to call Name after [Close].
func (*File)Read¶
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¶
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)ReadDir¶added ingo1.16
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)Readdir¶
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¶
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¶
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)SetDeadline¶added ingo1.10
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)SetReadDeadline¶added ingo1.10
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)SetWriteDeadline¶added ingo1.10
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¶
Stat returns theFileInfo structure describing file.If there is an error, it will be of type*PathError.
func (*File)Sync¶
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)SyscallConn¶added ingo1.12
SyscallConn returns a raw file.This implements the syscall.Conn interface.
func (*File)Truncate¶
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¶
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¶
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¶
WriteString is like Write, but writes the contents of string s rather thana slice of bytes.
typeFileInfo¶
A FileInfo describes a file and is returned byStat andLstat.
funcLstat¶
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.
typeFileMode¶
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¶
LinkError records an error during a link or symlink or renamesystem call and the paths 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¶
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¶
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¶
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¶
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¶
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)ExitCode¶added 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.
typeRoot¶added 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.
funcOpenRoot¶added ingo1.24.0
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)Chmod¶added ingo1.25.0
Chmod changes the mode of the named file in the root to mode.SeeChmod for more details.
func (*Root)Chown¶added ingo1.25.0
Chown changes the numeric uid and gid of the named file in the root.SeeChown for more details.
func (*Root)Chtimes¶added ingo1.25.0
Chtimes changes the access and modification times of the named file in the root.SeeChtimes for more details.
func (*Root)Close¶added ingo1.24.0
Close closes the Root.After Close is called, methods on Root return errors.
func (*Root)Create¶added ingo1.24.0
Create creates or truncates the named file in the root.SeeCreate for more details.
func (*Root)FS¶added ingo1.24.0
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)Lchown¶added ingo1.25.0
Lchown changes the numeric uid and gid of the named file in the root.SeeLchown for more details.
func (*Root)Link¶added ingo1.25.0
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)Lstat¶added ingo1.24.0
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)Mkdir¶added ingo1.24.0
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)MkdirAll¶added ingo1.25.0
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)Name¶added ingo1.24.0
Name returns the name of the directory presented to OpenRoot.
It is safe to call Name after [Close].
func (*Root)Open¶added ingo1.24.0
Open opens the named file in the root for reading.SeeOpen for more details.
func (*Root)OpenFile¶added ingo1.24.0
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)OpenRoot¶added ingo1.24.0
OpenRoot opens the named directory in the root.If there is an error, it will be of type*PathError.
func (*Root)ReadFile¶added ingo1.25.0
ReadFile reads the named file in the root and returns its contents.SeeReadFile for more details.
func (*Root)Readlink¶added ingo1.25.0
Readlink returns the destination of the named symbolic link in the root.SeeReadlink for more details.
func (*Root)Remove¶added ingo1.24.0
Remove removes the named file or (empty) directory in the root.SeeRemove for more details.
func (*Root)RemoveAll¶added ingo1.25.0
RemoveAll removes the named file or directory and any children that it contains.SeeRemoveAll for more details.
func (*Root)Rename¶added ingo1.25.0
Rename renames (moves) oldname to newname.Both paths are relative to the root.SeeRename for more details.
func (*Root)Stat¶added ingo1.24.0
Stat returns aFileInfo describing the named file in the root.SeeStat for more details.
func (*Root)Symlink¶added ingo1.25.0
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.
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¶
SyscallError records an error from a specific system call.
func (*SyscallError)Error¶
func (e *SyscallError) Error()string
func (*SyscallError)Timeout¶added ingo1.10
func (e *SyscallError) Timeout()bool
Timeout reports whether this error represents a timeout.
func (*SyscallError)Unwrap¶added ingo1.13
func (e *SyscallError) Unwrap()error
Source Files¶
- dir.go
- dir_unix.go
- dirent_linux.go
- eloop_other.go
- env.go
- error.go
- error_errno.go
- exec.go
- exec_linux.go
- exec_posix.go
- exec_unix.go
- executable.go
- executable_procfs.go
- file.go
- file_open_unix.go
- file_posix.go
- file_unix.go
- getwd.go
- path.go
- path_unix.go
- pidfd_linux.go
- pipe2_unix.go
- proc.go
- rawconn.go
- removeall_at.go
- removeall_unix.go
- root.go
- root_nonwindows.go
- root_openat.go
- root_unix.go
- stat.go
- stat_linux.go
- stat_unix.go
- sticky_notbsd.go
- sys.go
- sys_linux.go
- sys_unix.go
- tempfile.go
- types.go
- types_unix.go
- wait_waitid.go
- zero_copy_linux.go
- zero_copy_posix.go
Directories¶
| Path | Synopsis |
|---|---|
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. |