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)){"env":"prod"}The idiomatic existence check.
func ensureDir(path string) error {
_, err := os.Stat(path)
if errors.Is(err, fs.ErrNotExist) {
return os.MkdirAll(path, 0750)
}
return err
}
err := ensureDir("./data/logs")
fmt.Println(err)Copies bytes without loading the whole file into memory.
src, err := os.Open("input.csv")
if err != nil {
log.Fatal(err)
}
defer src.Close()
dst, err := os.Create("input.csv.bak")
if err != nil {
log.Fatal(err)
}
defer dst.Close()
written, err := io.Copy(dst, src)
if err != nil {
log.Fatal(err)
}
fmt.Println("copied", written, "bytes")copied 843 bytesFunctions
| Function | Description |
|---|---|
Open(name string) (*File, error) | Check err, then defer f.Close(). |
Three calls open a file and the flags are the only real difference. | |
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. |
The whole file lands in memory, which is what you want for config and what you do not want for a log. Past a few megabytes, open it and stream instead: a | |
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. |
A missing file and an unreadable one both come back as an error, and telling them apart is the whole job. | |
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. |
Both read the same variable. | |
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.
| Type | Description |
|---|---|
type File struct22 methods | An open file. Everything you do to it goes through a method. |
Read(b []byte) (n int, err error) Fills b from the current offset and moves the offset forward. Returns io.EOF at the end. ReadAt(b []byte, off int64) (n int, err error) Reads from a fixed offset and leaves the file offset alone, so several goroutines can read at once. ReadFrom(r io.Reader) (n int64, err error) Drains r into the file. io.Copy finds this and uses it, which is how a copy can reach the kernel's own fast path. Write(b []byte) (n int, err error) Writes all of b, or returns an error saying why it could not. WriteAt(b []byte, off int64) (n int, err error) Writes at a fixed offset, leaving the file offset alone. WriteString(s string) (n int, err error) Writes a string without the []byte conversion. WriteTo(w io.Writer) (n int64, err error) Pushes the rest of the file into w. Seek(offset int64, whence int) (ret int64, err error) Moves the offset relative to io.SeekStart, io.SeekCurrent, or io.SeekEnd, and reports where it landed. Close() error Releases the descriptor. On a file you wrote, the error here is the one that reports a failed flush, so check it. Name() string The name the file was opened with, which is what CreateTemp callers use to find the random path. Stat() (FileInfo, error) Size, mode, and modification time, read through the open handle rather than the path. Sync() error Blocks until the file's contents are on the disk rather than in the kernel's cache. Truncate(size int64) error Resizes the file. The offset stays where it was. Chmod(mode FileMode) error Changes permission bits through the open handle. Chown(uid, gid int) error Changes owner and group. Chdir() error Makes this directory the process working directory. Fd() uintptr The raw descriptor, for handing to syscall or cgo. ReadDir(n int) ([]DirEntry, error) Reads at most n entries from an open directory, so a huge directory can be walked in batches. n <= 0 reads all of it. SetDeadline(t time.Time) error Fails reads and writes after t. Pipes and terminals honor it; regular files do not. SetReadDeadline(t time.Time) error The deadline for reads only. SetWriteDeadline(t time.Time) error The deadline for writes only. SyscallConn() (syscall.RawConn, error) The raw connection, for a syscall Go does not wrap. Satisfies io.Reader, io.Writer, io.Closer, io.Seeker, io.ReaderAt, io.WriterAt, io.ReaderFrom, io.WriterTo, io.StringWriter A handle is a reader, a writer, and a seeker at once, so anything in the standard library that takes one of those interfaces takes a file. | |
type FileInfo interface6 methods | What Stat tells you about a file. |
Name() string The base name, with no directory in front of it. Size() int64 Length in bytes, for a regular file. Mode() FileMode Permission bits plus the type bits that say directory, symlink, or device. ModTime() time.Time When the contents last changed. IsDir() bool Short for Mode().IsDir(). Sys() any The platform's own struct underneath, *syscall.Stat_t on Unix. May be nil. Implemented by the unexported values os.Stat returns, plus every fs.FS implementation Six methods and no fields, so everything comes through a call. | |
type DirEntry interface4 methods | One entry from a directory listing. |
Name() string The base name of the entry. IsDir() bool Whether the entry is a directory. Type() FileMode Only the type bits, which is enough to tell a directory or symlink from a regular file. Info() (FileInfo, error) The full FileInfo, including size and modification time. Implemented by the values os.ReadDir returns, plus every fs.FS implementation The name and the type bits arrive with the listing itself, so testing | |
type FileMode uint325 methods | Permission bits and type bits in one value. |
IsDir() bool Whether the directory bit is set. IsRegular() bool Whether this is an ordinary file, with no type bits set at all. Perm() FileMode Just the permission bits, with the type bits masked off. Type() FileMode Just the type bits, with the permissions masked off. String() string The ls-style rendering, "drwxr-xr-x". Satisfies fmt.Stringer One integer holding two unrelated things. Printing it gives the | |
type Root struct23 methods | A directory every path is resolved inside of. |
Open(name string) (*File, error) Opens a file inside the root, read-only. Create(name string) (*File, error) Creates or truncates a file inside the root. OpenFile(name string, flag int, perm FileMode) (*File, error) The explicit-flags form, confined to the root. OpenRoot(name string) (*Root, error) A root nested inside this one. ReadFile(name string) ([]byte, error) Whole file in memory, confined to the root. WriteFile(name string, data []byte, perm FileMode) error Whole file written, confined to the root. Stat(name string) (FileInfo, error) Follows symlinks, but only ones that stay inside the root. Lstat(name string) (FileInfo, error) Describes the link itself. Mkdir(name string, perm FileMode) error One directory level. MkdirAll(name string, perm FileMode) error Every missing parent along the path. Remove(name string) error One file or empty directory. RemoveAll(name string) error The path and everything under it. Rename(oldname, newname string) error Both paths have to be inside the root. Symlink(oldname, newname string) error Creates a link inside the root. Readlink(name string) (string, error) Reads a link's target. Link(oldname, newname string) error Creates a hard link. Chmod(name string, mode FileMode) error Permission bits. Chown(name string, uid, gid int) error Owner and group. Lchown(name string, uid, gid int) error Owner and group of the link itself. Chtimes(name string, atime, mtime time.Time) error Access and modification times. FS() fs.FS The root as a read-only fs.FS, for template.ParseFS and friends. Name() string The directory the root was opened on. Close() error Releases the directory handle. Every method takes a path and resolves it inside the directory, so a name that climbs out fails instead of succeeding somewhere it should not. This is the answer for any filename that came from a request. | |
type Process struct4 methods | A handle on a running process. |
Signal(sig Signal) error Sends a signal. This is where a FindProcess on a dead pid finally reports os.ErrProcessDone. Kill() error Sends SIGKILL. The process gets no chance to clean up. Wait() (*ProcessState, error) Blocks until the process exits, then reports how it went. Only works on a process you started. Release() error Drops the handle without waiting, so the OS can reclaim it. A handle you signal and then wait on. | |
type ProcessState struct9 methods | How a finished process finished. |
ExitCode() int The status the process exited with. -1 when a signal killed it or it is still running. Exited() bool Whether it exited on its own rather than being signalled. Success() bool Short for an exit code of zero. Pid() int The process id. SystemTime() time.Duration CPU time spent in the kernel. UserTime() time.Duration CPU time spent in the program itself. Sys() any The platform's own status value, syscall.WaitStatus on Unix. SysUsage() any The platform's resource usage, *syscall.Rusage on Unix. String() string A readable summary, "exit status 1" or "signal: killed". Satisfies fmt.Stringer What | |
type Signal interface2 methods | An operating system signal. |
String() string The signal's name, "interrupt". Signal() Carries no behavior. It is there so an ordinary Stringer cannot be passed by mistake. Implemented by syscall.Signal on Unix, which is what os.Interrupt and os.Kill are Signals arrive on a channel you register with | |
type PathError struct3 methods | What a failed file operation actually returns. |
Error() string The three fields joined, "open a.txt: no such file or directory". Unwrap() error The underlying error, which is what errors.Is(err, fs.ErrNotExist) compares against. Timeout() bool Whether the failure was a deadline expiring. Satisfies error
| |
Values
| Value | Description |
|---|---|
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. |
| |