package os
import "os"
Package os provides a platform-independent interface to operating system functionality. The design is Unix-like, although the error handling is Go-like; failing calls return values of type error rather than error numbers. Often, more information is available within the error. For example, if a call that takes a file name fails, such as Open or Stat, the error will include the failing file name when printed and will be of type *PathError, which may be unpacked for more information.
The 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 and Write 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])
Index ¶
- Constants
- Variables
- func Chdir(dir string) error
- func Clearenv()
- func Environ() []string
- 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 IsPermission(err error) bool
- func Mkdir(name string, perm FileMode) error
- func MkdirAll(path string, perm FileMode) error
- func NewSyscallError(syscall string, err error) error
- func RemoveAll(path string) error
- func Rename(oldpath, newpath string) error
- func SameFile(fi1, fi2 FileInfo) bool
- func Setenv(key, value string) error
- type FileInfo
- type FileMode
- func (m FileMode) IsDir() bool
- func (m FileMode) IsRegular() bool
- func (m FileMode) Perm() FileMode
- func (m FileMode) String() string
- type LinkError
- type PathError
- type ProcAttr
- type Process
- func FindProcess(pid int) (p *Process, err error)
- func StartProcess(name string, argv []string, attr *ProcAttr) (*Process, error)
- func (p *Process) Kill() error
- func (p *Process) Release() error
- func (p *Process) Signal(sig Signal) error
- func (p *Process) Wait() (*ProcessState, error)
- type Signal
- type SyscallError
Constants ¶
const ( O_RDONLY int = syscall.O_RDONLY // open the file read-only. O_WRONLY int = syscall.O_WRONLY // open the file write-only. O_RDWR int = syscall.O_RDWR // open the file read-write. O_APPEND int = syscall.O_APPEND // append data to the file when writing. O_CREATE int = syscall.O_CREAT // create a new file if none exists. O_EXCL int = syscall.O_EXCL // used with O_CREATE, file must not exist O_SYNC int = syscall.O_SYNC // open for synchronous I/O. O_TRUNC int = syscall.O_TRUNC // if possible, truncate file when opened. )
Flags to Open wrapping those of the underlying system. Not all flags may be implemented on a given system.
const ( SEEK_SET int = 0 // seek relative to the origin of the file SEEK_CUR int = 1 // seek relative to the current offset SEEK_END int = 2 // seek relative to the end )
Seek whence values.
Variables ¶
var ( ErrInvalid = errors.New("invalid argument") ErrPermission = errors.New("permission denied") ErrExist = errors.New("file already exists") ErrNotExist = errors.New("file does not exist") )
Portable analogs of some common system call errors.
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.
var Args []string
Args hold the command-line arguments, starting with the program name.
Functions ¶
func Chdir ¶
Chdir changes the current working directory to the named directory. If there is an error, it will be of type *PathError.
func Clearenv ¶
func Clearenv()
Clearenv deletes all environment variables.
func Environ ¶
func Environ() []string
Environ returns a copy of strings representing the environment, in the form "key=value".
func Exit ¶
func Exit(code int)
Exit causes the current program to exit with the given status code. Conventionally, code zero indicates success, non-zero an error. The program terminates immediately; deferred functions are not run.
func Expand ¶
Expand replaces ${var} or $var in the string based on the mapping function. For example, os.ExpandEnv(s) is equivalent to os.Expand(s, os.Getenv).
func ExpandEnv ¶
ExpandEnv replaces ${var} or $var in the string according to the values of the current environment variables. References to undefined variables are replaced by the empty string.
func Getegid ¶
func Getegid() int
Getegid returns the numeric effective group id of the caller.
func Getenv ¶
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.
func Geteuid ¶
func Geteuid() int
Geteuid returns the numeric effective user id of the caller.
func Getgid ¶
func Getgid() int
Getgid returns the numeric group id of the caller.
func Getgroups ¶
Getgroups returns a list of the numeric ids of groups that the caller belongs to.
func Getpagesize ¶
func Getpagesize() int
Getpagesize returns the underlying system's memory page size.
func Getpid ¶
func Getpid() int
Getpid returns the process id of the caller.
func Getppid ¶
func Getppid() int
Getppid returns the process id of the caller's parent.
func Getuid ¶
func Getuid() int
Getuid returns the numeric user id of the caller.
func Getwd ¶
Getwd returns a rooted path name corresponding to the current directory. If the current directory can be reached via multiple paths (due to symbolic links), Getwd may return any one of them.
func Hostname ¶
Hostname returns the host name reported by the kernel.
func IsExist ¶
IsExist returns a boolean indicating whether the error is known to report that a file or directory already exists. It is satisfied by ErrExist as well as some syscall errors.
func IsNotExist ¶
IsNotExist returns a boolean indicating whether the error is known to report that a file or directory does not exist. It is satisfied by ErrNotExist as well as some syscall errors.
func IsPermission ¶
IsPermission returns a boolean indicating whether the error is known to report that permission is denied. It is satisfied by ErrPermission as well as some syscall errors.
func Mkdir ¶
Mkdir creates a new directory with the specified name and permission bits. If there is an error, it will be of type *PathError.
func MkdirAll ¶
MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error. The permission bits perm are used for all directories that MkdirAll creates. If path is already a directory, MkdirAll does nothing and returns nil.
func NewSyscallError ¶
NewSyscallError returns, as an error, a new SyscallError with the given system call name and error details. As a convenience, if err is nil, NewSyscallError returns nil.
func RemoveAll ¶
RemoveAll removes path and any children it contains. It removes everything it can but returns the first error it encounters. If the path does not exist, RemoveAll returns nil (no error).
func Rename ¶
Rename renames (moves) a file. OS-specific restrictions might apply.
func SameFile ¶
SameFile reports whether fi1 and fi2 describe the same file. For example, on Unix this means that the device and inode fields of the two underlying structures are identical; on other systems the decision may be based on the path names. SameFile only applies to results returned by this package's Stat. It returns false in other cases.
func Setenv ¶
Setenv sets the value of the environment variable named by the key. It returns an error, if any.
Types ¶
type FileInfo ¶
type FileInfo interface { Name() string // base name of the file Size() int64 // length in bytes for regular files; system-dependent for others Mode() FileMode // file mode bits ModTime() time.Time // modification time IsDir() bool // abbreviation for Mode().IsDir() Sys() interface{} // underlying data source (can return nil) }
A FileInfo describes a file and is returned by Stat and Lstat.
type FileMode ¶
type FileMode uint32
A FileMode represents a file's mode and permission bits. The bits have the same definition on all systems, so that information about files can be moved from one system to another portably. Not all bits apply to all systems. The only required bit is ModeDir for directories.
const ( // The single letters are the abbreviations // used by the String method's formatting. ModeDir FileMode = 1 << (32 - 1 - iota) // d: is a directory ModeAppend // a: append-only ModeExclusive // l: exclusive use ModeTemporary // T: temporary file (not backed up) ModeSymlink // L: symbolic link ModeDevice // D: device file ModeNamedPipe // p: named pipe (FIFO) ModeSocket // S: Unix domain socket ModeSetuid // u: setuid ModeSetgid // g: setgid ModeCharDevice // c: Unix character device, when ModeDevice is set ModeSticky // t: sticky // Mask for the type bits. For regular files, none will be set. ModeType = ModeDir | ModeSymlink | ModeNamedPipe | ModeSocket | ModeDevice ModePerm FileMode = 0777 // permission bits )
The defined file mode bits are the most significant bits of the FileMode. The nine least-significant bits are the standard Unix rwxrwxrwx permissions. The values of these bits should be considered part of the public API and may be used in wire protocols or disk representations: they must not be changed, although new bits might be added.
func (FileMode) IsDir ¶
IsDir reports whether m describes a directory. That is, it tests for the ModeDir bit being set in m.
func (FileMode) IsRegular ¶
IsRegular reports whether m describes a regular file. That is, it tests that no mode type bits are set.
func (FileMode) Perm ¶
Perm returns the Unix permission bits in m.
func (FileMode) String ¶
type LinkError ¶
LinkError records an error during a link or symlink or rename system call and the paths that caused it.
func (*LinkError) Error ¶
type PathError ¶
PathError records an error and the operation and file path that caused it.
func (*PathError) Error ¶
type ProcAttr ¶
type ProcAttr struct { // If Dir is non-empty, the child changes into the directory before // creating the process. Dir string // If Env is non-nil, it gives the environment variables for the // 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. 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 process started by StartProcess.
type Process ¶
type Process struct { Pid int // contains filtered or unexported fields }
Process stores the information about a process created by StartProcess.
func FindProcess ¶
FindProcess looks for a running process by its pid. The Process it returns can be used to obtain information about the underlying operating system process.
func StartProcess ¶
StartProcess starts a new process with the program, arguments and attributes specified by name, argv and attr.
StartProcess is a low-level interface. The os/exec package provides higher-level interfaces.
If there is an error, it will be of type *PathError.
func (*Process) Kill ¶
Kill causes the Process to exit immediately.
func (*Process) Release ¶
Release releases any resources associated with the Process p, rendering it unusable in the future. Release only needs to be called if Wait is not.
func (*Process) Signal ¶
Signal sends a signal to the Process. Sending Interrupt on Windows is not implemented.
func (*Process) Wait ¶
Wait waits for the Process to exit, and then returns a ProcessState describing its status and an error, if any. Wait releases any resources associated with the Process. On most operating systems, the Process must be a child of the current process or an error will be returned.
type Signal ¶
type Signal interface { String() string Signal() // to distinguish from other Stringers }
A Signal represents an operating system signal. The usual underlying implementation is operating system-dependent: on Unix it is syscall.Signal.
type SyscallError ¶
SyscallError records an error from a specific system call.
func (*SyscallError) Error ¶
func (e *SyscallError) Error() string
Source Files ¶
doc.go env.go error.go exec.go file.go getwd.go path.go proc.go types.go types_notwin.go
Directories ¶
Path | Synopsis |
---|---|
os/exec | Package exec runs external commands. |
os/signal | Package signal implements access to incoming signals. |
os/user | Package user allows user account lookups by name or id. |
- Version
- v1.3.0
- Published
- Jun 19, 2014
- Platform
- js/wasm
- Imports
- 7 packages
- Last checked
- 36 seconds ago –
Tools for package owners.