os

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 5, 2026 License: BSD-3-Clause Imports: 8 Imported by: 0

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

Examples

Constants

View Source
const MaxNameLen = 256

MaxNameLen is the maximum length of a filename.

View Source
const MaxPathLen = 4096

MaxPathLen is the maximum length of a path.

View Source
const O_APPEND = 0x00000008 // open the file in append mode
View Source
const O_CREATE = 0x00000200 // create a new file if none exists
View Source
const O_EXCL = 0x00000800 // ensure that this call creates the file
View Source
const O_RDONLY = 0x0000 // open the file read-only

Open flag constants.

View Source
const O_RDWR = 0x0002 // open the file read-write
View Source
const O_SYNC = 0x0080 // synchronous writes
View Source
const O_TRUNC = 0x00000400 // truncate regular writable file when opened
View Source
const O_WRONLY = 0x0001 // open the file write-only

Variables

View Source
var Args []string

Args holds the command-line arguments, starting with the program name.

View Source
var ErrClosed = errors.New("os: file already closed")

IO-related errors that can be returned by functions in this package.

View Source
var ErrExist = errors.New("os: file already exists")
View Source
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.

View Source
var ErrIsDir = errors.New("os: is a directory")
View Source
var ErrNotDir = errors.New("os: not a directory")
View Source
var ErrNotExist = errors.New("os: no such file or directory")
View Source
var ErrPermission = errors.New("os: permission denied")

Functions

func Chdir

func Chdir(dir string) error

Chdir changes the current working directory to the named directory.

func Chmod

func Chmod(name string, mode FileMode) error

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

func Chown(name string, uid, gid int) error

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

func Chtimes(name string, atime time.Time, mtime time.Time) error

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

func FreeDirEntry(a mem.Allocator, entries []DirEntry)

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 Getegid

func Getegid() int

Getegid returns the numeric effective group id of the caller.

func Getenv

func Getenv(key string) string

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 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 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

func Getwd(buf []byte) (string, error)

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

func Hostname(buf []byte) (string, error)

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

func Lchown(name string, uid, gid int) error

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 Link(oldname, newname string) error

Link creates newname as a hard link to the oldname file.

func LookupEnv

func LookupEnv(key string) (string, bool)

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

func Mkdir(name string, perm FileMode) error

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

func MkdirTemp(buf []byte, dir, pattern string) (string, error)

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

func ReadFile(a mem.Allocator, name string) ([]byte, error)

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(buf []byte, name string) (string, error)

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.

func Remove

func Remove(name string) error

Remove removes the named file or (empty) directory.

func Rename

func Rename(oldpath, newpath string) error

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

func SameFile(fi1, fi2 FileInfo) bool

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

func Setenv(key, value string) error

Setenv sets the value of the environment variable named by the key. It returns an error, if any.

func Symlink(oldname, newname string) error

Symlink creates newname as a symbolic link to oldname.

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

func Truncate(name string, size int64) error

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

func Unsetenv(key string) error

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

func WriteFile(name string, data []byte, perm FileMode) error

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

func ReadDir(a mem.Allocator, name string) ([]DirEntry, error)

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)
	}
}

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

func Create(name string) (File, error)

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

func CreateTemp(buf []byte, dir, pattern string) (File, error)

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

func Open(name string) (File, error)

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

func OpenFile(name string, flag int, perm FileMode) (File, error)

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

func (f *File) Close() error

Close closes the file, rendering it unusable for I/O. Close will return an error if it has already been called.

func (*File) Name

func (f *File) Name() string

Name returns the name of the file as presented to Open/Create.

func (*File) Read

func (f *File) Read(b []byte) (int, error)

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

func (f *File) ReadAt(b []byte, off int64) (int, error)

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

func (f *File) Seek(offset int64, whence int) (int64, error)

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

func (f *File) Write(b []byte) (int, error)

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

func (f *File) WriteAt(b []byte, off int64) (int, error)

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.

func (*File) WriteString

func (f *File) WriteString(s string) (int, error)

WriteString is like Write, but writes the contents of string s rather than a slice of bytes.

type FileInfo

type FileInfo struct {
	// contains filtered or unexported fields
}

A FileInfo describes a file and is returned by Stat and Lstat.

func Lstat

func Lstat(name string) (FileInfo, error)

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.

func Stat

func Stat(name string) (FileInfo, error)

Stat returns a FileInfo describing the named file.

func (*FileInfo) IsDir

func (fi *FileInfo) IsDir() bool

IsDir reports whether the file is a directory.

func (*FileInfo) ModTime

func (fi *FileInfo) ModTime() time.Time

ModTime returns the modification time.

func (*FileInfo) Mode

func (fi *FileInfo) Mode() FileMode

Mode returns the file mode bits.

func (*FileInfo) Name

func (fi *FileInfo) Name() string

Name returns the base name of the file.

func (*FileInfo) Size

func (fi *FileInfo) Size() int64

Size returns the length in bytes for regular files; system-dependent for others.

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.

func (FileMode) IsDir

func (m FileMode) IsDir() bool

IsDir reports whether m describes a directory.

func (FileMode) IsRegular

func (m FileMode) IsRegular() bool

IsRegular reports whether m describes a regular file.

func (FileMode) Perm

func (m FileMode) Perm() FileMode

Perm returns the Unix permission bits in m.

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL