HowtoGo
Home / Standard Library / The os Package
Standard Library

The os Package

os gives platform-independent access to files, environment variables, and process state. Use ReadFile/WriteFile when a file fits comfortably in memory, and Open/Create with streaming otherwise.

Examples

Skips open/close boilerplate for small files.

err := os.WriteFile("config.json", []byte("{\"env\":\"prod\"}"), 0644)
if err != nil {
    log.Fatal(err)
}

data, err := os.ReadFile("config.json")
if err != nil {
    log.Fatal(err)
}
fmt.Println(string(data))
Output
{"env":"prod"}

Functions

FunctionDescription
Open(name string) (*File, error)
Check err, then defer f.Close().
Create(name string) (*File, error)
f, err := os.Create("a.txt")
Truncates if it exists. defer f.Close().
OpenFile(name string, flag int, perm FileMode) (*File, error)
f, err := os.OpenFile(n, os.O_APPEND, 0644)
Like Open/Create, with explicit flags.
CreateTemp(dir, pattern string) (*File, error)
f, err := os.CreateTemp("", "upload-*.json")
Random name, opened for you. Remove it yourself.
Pipe() (r *File, w *File, err error)
r, w, err := os.Pipe()
A connected pair of files, in memory.
ReadFile(name string) ([]byte, error)
Whole file in memory. Check err first.
WriteFile(name string, data []byte, perm FileMode) error
err := os.WriteFile("a.txt", b, 0644)
Error only, the write already happened.
Stat(name string) (FileInfo, error)
info.Size(), info.IsDir() once err is nil.
Lstat(name string) (FileInfo, error)
info, err := os.Lstat("link")
Describes the symlink itself, not its target.
SameFile(fi1, fi2 FileInfo) bool
same := os.SameFile(a, b)
True when both describe one file on disk.
Rename(oldpath, newpath string) error
err := os.Rename("a.tmp", "a.txt")
Moves a file. Replaces the destination.
Truncate(name string, size int64) error
err := os.Truncate("log.txt", 0)
Resizes by path, without opening the file.
Chmod(name string, mode FileMode) error
err := os.Chmod("run.sh", 0755)
Sets permission bits on an existing path.
Remove(name string) error
err := os.Remove("a.txt")
Deletes one file or empty dir.
RemoveAll(path string) error
err := os.RemoveAll("tmp/")
Deletes the path and everything under it.
Mkdir(name string, perm FileMode) error
err := os.Mkdir("logs", 0750)
Fails if the parent doesn't exist.
MkdirAll(path string, perm FileMode) error
err := os.MkdirAll("a/b/c", 0750)
Creates parents too. Safe if it exists.
MkdirTemp(dir, pattern string) (string, error)
dir, err := os.MkdirTemp("", "build-*")
Random directory name. Remove it yourself.
ReadDir(name string) ([]DirEntry, error)
entries, err := os.ReadDir(".")
Range over the result, call entry.Name().
Getwd() (string, error)
cwd, err := os.Getwd()
The process working directory, absolute.
Chdir(dir string) error
err := os.Chdir("/srv/app")
Changes the working directory, process-wide.
TempDir() string
dir := os.TempDir()
/tmp on Unix, honoring $TMPDIR.
DirFS(dir string) fs.FS
fsys := os.DirFS("./static")
Turns a directory into an fs.FS.
Symlink(oldname, newname string) error
err := os.Symlink("v2", "current")
Creates newname pointing at oldname.
Readlink(name string) (string, error)
target, err := os.Readlink("current")
Reads a symlink's target.
Getenv(key string) string
port := os.Getenv("PORT")
Empty string if unset. No error.
LookupEnv(key string) (string, bool)
Check the bool, not the string.
Setenv(key, value string) error
err := os.Setenv("TZ", "UTC")
Sets a variable for this process only.
Unsetenv(key string) error
err := os.Unsetenv("DEBUG")
Removes a variable from the environment.
Environ() []string
for _, kv := range os.Environ() {}
Every variable as "KEY=value".
ExpandEnv(s string) string
p := os.ExpandEnv("$HOME/.config")
Substitutes $VAR and ${VAR} in a string.
UserHomeDir() (string, error)
home, err := os.UserHomeDir()
$HOME on Unix, %USERPROFILE% on Windows.
UserConfigDir() (string, error)
dir, err := os.UserConfigDir()
Where per-user config belongs.
Exit(code int)
os.Exit(1)
Deferred calls never run.
Getpid() int
pid := os.Getpid()
This process's id.
Hostname() (string, error)
host, err := os.Hostname()
The name the kernel reports for the host.
Executable() (string, error)
exe, err := os.Executable()
Path of the running binary.
FindProcess(pid int) (*Process, error)
p, err := os.FindProcess(pid)
A handle for signalling an existing process.
OpenRoot(name string) (*Root, error)
root, err := os.OpenRoot("./uploads")
Confines every path operation to one directory.

Types

Open a row for the type's full method set.

TypeDescription
type File struct22 methods
An open file. Everything you do to it goes through a method.
type FileInfo interface6 methods
What Stat tells you about a file.
type DirEntry interface4 methods
One entry from a directory listing.
type FileMode uint325 methods
Permission bits and type bits in one value.
type Root struct23 methods
A directory every path is resolved inside of.
type Process struct4 methods
A handle on a running process.
type ProcessState struct9 methods
How a finished process finished.
type Signal interface2 methods
An operating system signal.
type PathError struct3 methods
What a failed file operation actually returns.

Values

ValueDescription
Args []string
name := os.Args[1]
Command-line arguments. Args[0] is the binary path.
Stdin *File
s := bufio.NewScanner(os.Stdin)
Standard input, already open.
Stdout *File
fmt.Fprintln(os.Stdout, "ready")
Standard output, already open.
Stderr *File
fmt.Fprintln(os.Stderr, "failed")
Standard error, already open.
ErrNotExist error
errors.Is(err, os.ErrNotExist)
The path was not there.
ErrExist error
errors.Is(err, os.ErrExist)
The path was already there.
ErrPermission error
errors.Is(err, os.ErrPermission)
The process is not allowed to do that.
ErrClosed error
errors.Is(err, os.ErrClosed)
The file was already closed.
ErrProcessDone error
errors.Is(err, os.ErrProcessDone)
The process had already exited.
Interrupt, Kill Signal
signal.Notify(c, os.Interrupt)
The two signals every platform has.
O_RDONLY, O_WRONLY, O_RDWR, O_APPEND, O_CREATE, O_EXCL, O_TRUNC int
os.O_WRONLY|os.O_CREATE|os.O_APPEND
The flags OpenFile takes, combined with |.
ModePerm FileMode
perm := info.Mode() & os.ModePerm
The permission bits mask, 0777.
PathSeparator rune
string(os.PathSeparator)
'/' on Unix, '\' on Windows.
DevNull string
f, err := os.Open(os.DevNull)
The platform's discard file.