Documentation
¶
Overview ¶
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.
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 Exit(code int)
- func FreeDirEntry(a mem.Allocator, entries []DirEntry)
- func Getegid() int
- func Getenv(key string) string
- func Geteuid() int
- func Getgid() int
- func Getpid() int
- func Getppid() int
- func Getuid() int
- func Getwd(buf []byte) (string, error)
- func Hostname(buf []byte) (string, error)
- 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 MkdirTemp(buf []byte, dir, pattern string) (string, error)
- func ReadFile(a mem.Allocator, name string) ([]byte, error)
- func Readlink(buf []byte, name string) (string, error)
- func Remove(name 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 WriteFile(name string, data []byte, perm FileMode) error
- type DirEntry
- type File
- func (f *File) Close() error
- func (f *File) Name() string
- func (f *File) Read(b []byte) (int, error)
- func (f *File) ReadAt(b []byte, off int64) (int, error)
- func (f *File) Seek(offset int64, whence int) (int64, error)
- func (f *File) Write(b []byte) (int, error)
- func (f *File) WriteAt(b []byte, off int64) (int, error)
- func (f *File) WriteString(s string) (int, error)
- type FileInfo
- type FileInfoResult
- type FileMode
- type FileResult
Examples ¶
Constants ¶
const MaxNameLen = 256
MaxNameLen is the maximum length of a filename.
const MaxPathLen = 4096
MaxPathLen is the maximum length of a path.
const O_APPEND = 0x00000008 // open the file in append mode
const O_CREATE = 0x00000200 // create a new file if none exists
const O_EXCL = 0x00000800 // ensure that this call creates the file
const O_RDONLY = 0x0000 // open the file read-only
Open flag constants.
const O_RDWR = 0x0002 // open the file read-write
const O_SYNC = 0x0080 // synchronous writes
const O_TRUNC = 0x00000400 // truncate regular writable file when opened
const O_WRONLY = 0x0001 // open the file write-only
Variables ¶
var Args []string
Args holds the command-line arguments, starting with the program name.
var ErrClosed = errors.New("os: file already closed")
IO-related errors that can be returned by functions in this package.
var ErrExist = errors.New("os: file already exists")
var ErrIO = errors.New("os: i/o error")
ErrIO is a generic I/O error that is returned when the error does not match any of the other, more specific errors.
var ErrIsDir = errors.New("os: is a directory")
var ErrNotDir = errors.New("os: not a directory")
var ErrNotExist = errors.New("os: no such file or directory")
var ErrPermission = errors.New("os: permission denied")
Functions ¶
func Chmod ¶
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.
Example ¶
package main
import (
"solod.dev/so/fmt"
"solod.dev/so/os"
)
func main() {
if err := os.Chmod("some-filename", 0644); err != nil {
panic(err)
}
fmt.Println("ok")
}
Output: ok
func Chown ¶
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.
func Chtimes ¶
Chtimes changes the access and modification times of the named file, similar to the Unix utime() or utimes() functions. A zero time.Time value will leave the corresponding file time unchanged.
Example ¶
package main
import (
"solod.dev/so/fmt"
"solod.dev/so/os"
"solod.dev/so/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 {
panic(err)
}
fmt.Println("ok")
}
Output: ok
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.
func FreeDirEntry ¶
FreeDirEntry frees a slice of DirEntry previously returned by ReadDir. It frees each entry's Name string and the slice itself.
If the allocator is nil, uses the system allocator.
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. The returned string is a view into the static environment buffer; the caller must not modify or free it.
Example ¶
package main
import (
"solod.dev/so/fmt"
"solod.dev/so/os"
)
func main() {
os.Setenv("NAME", "gopher")
os.Setenv("BURROW", "/usr/gopher")
name := os.Getenv("NAME")
println(name) // gopher
burrow := os.Getenv("BURROW")
println(burrow) // /usr/gopher
fmt.Println("ok")
}
Output: ok
func Getwd ¶
Getwd returns an absolute path name corresponding to the current directory.
Writes the result into buf. Panics if buf is empty. The returned string is a view into buf.
func Hostname ¶
Hostname returns the host name reported by the kernel.
Writes the result into buf. Panics if buf is empty. The returned string is a view into buf.
func Lchown ¶
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.
func LookupEnv ¶
LookupEnv retrieves the value of the environment variable named by the key. If the variable is present in the environment the value (which may be empty) is returned and the boolean is true. Otherwise the returned value will be empty and the boolean will be false.
The returned string is a view into the static environment buffer; the caller must not modify or free it.
Example ¶
package main
import (
"solod.dev/so/fmt"
"solod.dev/so/os"
)
func main() {
os.Setenv("SOME_KEY", "value")
os.Setenv("EMPTY_KEY", "")
val, ok := os.LookupEnv("SOME_KEY")
println(val, ok) // value true
val, ok = os.LookupEnv("EMPTY_KEY")
println(val, ok) // true
val, ok = os.LookupEnv("MISSING_KEY")
println(val, ok) // false
fmt.Println("ok")
}
Output: ok
func Mkdir ¶
Mkdir creates a new directory with the specified name and permission bits (before umask).
Example ¶
package main
import (
"solod.dev/so/fmt"
"solod.dev/so/os"
)
func main() {
err := os.Mkdir("testdir", 0750)
if err != nil && err != os.ErrExist {
panic(err)
}
err = os.WriteFile("testdir/testfile.txt", []byte("Hello, Gophers!"), 0660)
if err != nil {
panic(err)
}
fmt.Println("ok")
}
Output: ok
func MkdirTemp ¶
MkdirTemp creates a new temporary directory in the directory dir and returns the pathname of the new directory. The new directory's name is generated by adding a random string to the end of pattern. 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. It is the caller's responsibility to remove the directory when it is no longer needed.
Writes the path of the created directory into buf. Panics if buf is empty. The returned string is a view into buf.
Example ¶
package main
import (
"path/filepath"
"solod.dev/so/fmt"
"solod.dev/so/os"
)
func main() {
buf := make([]byte, 256)
dir, err := os.MkdirTemp(buf, "", "example")
if err != nil {
panic(err)
}
defer os.Remove(dir) // clean up
file := filepath.Join(dir, "tmpfile")
if err := os.WriteFile(file, []byte("content"), 0666); err != nil {
panic(err)
}
fmt.Println("ok")
}
Output: ok
func ReadFile ¶
ReadFile reads the named file and returns the contents. A successful call returns err == nil, not err == EOF. Because ReadFile reads the whole file, it does not treat an EOF from Read as an error to be reported.
If the allocator is nil, uses the system allocator. The returned slice is allocated; the caller owns it.
Example ¶
package main
import (
"solod.dev/so/fmt"
"solod.dev/so/os"
)
func main() {
data, err := os.ReadFile(nil, "testdata/hello")
if err != nil {
panic(err)
}
os.Stdout.Write(data)
fmt.Println("ok")
}
Output: ok
func Readlink ¶
Readlink returns the destination of the named symbolic link. If the link destination is relative, Readlink returns the relative path without resolving it to an absolute one.
Writes the result into buf. Panics if buf is empty. The returned string is a view into buf.
Example ¶
package main
import (
"path/filepath"
"solod.dev/so/errors"
"solod.dev/so/fmt"
"solod.dev/so/os"
)
func main() {
// Create a temporary directory.
buf := make([]byte, 256)
d, err := os.MkdirTemp(buf, "", "")
if err != nil {
panic(err)
}
defer os.Remove(d)
// Write a file in the temporary directory.
targetPath := filepath.Join(d, "hello.txt")
if err := os.WriteFile(targetPath, []byte("Hello, Gophers!"), 0644); err != nil {
panic(err)
}
defer os.Remove(targetPath)
// Create a symbolic link to the file.
linkPath := filepath.Join(d, "hello.link")
if err := os.Symlink("hello.txt", filepath.Join(d, "hello.link")); err != nil {
if err == errors.ErrUnsupported {
// Allow the example to run on platforms that do not support symbolic links.
return
}
panic(err)
}
defer os.Remove(linkPath)
// Readlink returns the relative path as passed to os.Symlink.
dst, err := os.Readlink(buf, linkPath)
if err != nil {
panic(err)
}
println(dst) // hello.txt
fmt.Println("ok")
}
Output: ok
func Rename ¶
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.
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.
func Setenv ¶
Setenv sets the value of the environment variable named by the key. It returns an error, if any.
func TempDir ¶
func TempDir() string
TempDir returns the default directory to use for temporary files. On Unix systems, it returns $TMPDIR if non-empty, else /tmp. The directory is neither guaranteed to exist nor have accessible permissions.
func Truncate ¶
Truncate changes the size of the named file. If the file is a symbolic link, it changes the size of the link's target.
func Unsetenv ¶
Unsetenv unsets a single environment variable.
Example ¶
package main
import (
"solod.dev/so/fmt"
"solod.dev/so/os"
)
func main() {
os.Setenv("TMPDIR", "/my/tmp")
defer os.Unsetenv("TMPDIR")
fmt.Println("ok")
}
Output: ok
func WriteFile ¶
WriteFile writes data to the named file, creating it if necessary. If the file does not exist, WriteFile creates it with permissions perm (before umask); otherwise WriteFile truncates it before writing, without changing permissions.
Since WriteFile requires multiple system calls to complete, a failure mid-operation can leave the file in a partially written state.
Example ¶
package main
import (
"solod.dev/so/fmt"
"solod.dev/so/os"
)
func main() {
err := os.WriteFile("testdata/hello", []byte("Hello, Gophers!"), 0666)
if err != nil {
panic(err)
}
fmt.Println("ok")
}
Output: ok
Types ¶
type DirEntry ¶
type DirEntry struct {
// Name of the file (or subdirectory) described by the entry.
// This is only the final element of the path (the base name), not the entire path.
// For example, Name would be "hello.go" not "home/gopher/hello.go".
Name string
// Whether the entry describes a directory.
IsDir bool
// Type bits for the entry (a subset of the usual [FileMode] bits).
Type FileMode
}
A DirEntry is an entry read from a directory (using the ReadDir function).
func ReadDir ¶
ReadDir reads the named directory, returning all its directory entries sorted by filename. If an error occurs reading the directory, returns the entries it was able to read before the error, along with the error.
If the allocator is nil, uses the system allocator. The returned slice and entry names are allocated; the caller owns them. Use FreeDirEntry to free the result.
Example ¶
package main
import (
"solod.dev/so/fmt"
"solod.dev/so/os"
)
func main() {
files, err := os.ReadDir(nil, ".")
if err != nil {
panic(err)
}
defer os.FreeDirEntry(nil, files)
for _, file := range files {
fmt.Println(file.Name)
}
}
Output:
type File ¶
type File struct {
// contains filtered or unexported fields
}
File represents an open file descriptor.
var Stderr *File
var Stdin *File
var Stdout *File
func Create ¶
Create creates or truncates the named file. If the file already exists, it is truncated. If the file does not exist, it is created with mode 0o666 (before umask). If successful, methods on the returned File can be used for I/O; the associated file descriptor has mode O_RDWR. The directory containing the file must already exist.
func CreateTemp ¶
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. The file is created with mode 0o600 (before umask).
If dir is the empty string, CreateTemp uses the default directory for temporary files, as returned by TempDir. 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.
Writes the path of the created file into buf. Panics if buf is empty. The name in the returned File is a view into buf.
Example ¶
package main
import (
"solod.dev/so/fmt"
"solod.dev/so/os"
)
func main() {
buf := make([]byte, 256)
f, err := os.CreateTemp(buf, "", "example")
if err != nil {
panic(err)
}
defer os.Remove(f.Name()) // clean up
if _, err := f.Write([]byte("content")); err != nil {
panic(err)
}
if err := f.Close(); err != nil {
panic(err)
}
fmt.Println("created", f.Name())
}
Output: created /tmp/exampleXXXXXX
func Open ¶
Open opens the named file for reading. If successful, methods on the returned file can be used for reading; the associated file descriptor has mode O_RDONLY.
func OpenFile ¶
OpenFile is the generalized open call; most users will use Open or Create instead. It opens the named file with specified flag (O_RDONLY etc.). If the file does not exist, and the O_CREATE flag is passed, it is created with mode perm (before umask); the containing directory must exist. If successful, methods on the returned File can be used for I/O.
Example ¶
package main
import (
"solod.dev/so/fmt"
"solod.dev/so/os"
)
func main() {
f, err := os.OpenFile("notes.txt", os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
panic(err)
}
if err := f.Close(); err != nil {
panic(err)
}
fmt.Println("opened", f.Name())
}
Output: opened notes.txt
Example (Append) ¶
package main
import (
"solod.dev/so/fmt"
"solod.dev/so/os"
)
func main() {
// If the file doesn't exist, create it, or append to the file
f, err := os.OpenFile("access.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
panic(err)
}
if _, err := f.Write([]byte("appended some data\n")); err != nil {
f.Close() // ignore error; Write error takes precedence
panic(err)
}
if err := f.Close(); err != nil {
panic(err)
}
fmt.Println("appended to", f.Name())
}
Output: appended to access.log
func (*File) Close ¶
Close closes the file, rendering it unusable for I/O. Close will return an error if it has already been called.
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).
func (*File) Seek ¶
Seek sets the offset for the next Read or Write on file to offset, interpreted according to whence: io.SeekStart means relative to the start of the file, io.SeekCurrent means relative to the current offset, and io.SeekEnd means relative to the end.
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).
type FileInfo ¶
type FileInfo struct {
// contains filtered or unexported fields
}
A FileInfo describes a file and is returned by Stat and Lstat.
func Lstat ¶
Lstat returns a FileInfo describing the named file. If the file is a symbolic link, the returned FileInfo describes the symbolic link. Lstat makes no attempt to follow the link.
type FileInfoResult ¶
type FileInfoResult struct {
// contains filtered or unexported fields
}
FileInfoResult is a helper struct for returning a FileInfo and an error from a function.
type FileMode ¶
type FileMode uint32
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.
Example ¶
package main
import (
"solod.dev/so/fmt"
"solod.dev/so/os"
)
func main() {
fi, err := os.Lstat("some-filename")
if err != nil {
panic(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&os.ModeSymlink != 0:
fmt.Println("symbolic link")
case mode&os.ModeNamedPipe != 0:
fmt.Println("named pipe")
}
}
Output: permissions: 0777 regular file
const ( ModeDir FileMode = 1 << (32 - 1 - 0) ModeSymlink FileMode = 1 << (32 - 1 - 1) ModeNamedPipe FileMode = 1 << (32 - 1 - 2) ModeSocket FileMode = 1 << (32 - 1 - 3) ModeDevice FileMode = 1 << (32 - 1 - 4) ModeCharDevice FileMode = 1 << (32 - 1 - 5) ModeSetuid FileMode = 1 << (32 - 1 - 6) ModeSetgid FileMode = 1 << (32 - 1 - 7) ModeSticky FileMode = 1 << (32 - 1 - 8) ModeIrregular FileMode = 1 << (32 - 1 - 9) )
The defined file mode bits are the most significant bits of the FileMode.
const ModePerm FileMode = 0o777
ModePerm is the Unix permission bits.
type FileResult ¶
type FileResult struct {
// contains filtered or unexported fields
}
FileResult is a helper struct for returning a File and an error from a function.