os
包是 Go 语言中用于与操作系统交互的标准库之一。
1. Constants
O_RDONLY
, O_WRONLY
, O_RDWR
: 用于文件打开时的读写权限。
O_CREATE
, O_EXCL
, O_TRUNC
: 用于文件创建时的选项。
ModePerm
: 文件权限位掩码,表示所有权限。
2. Variables
Args
: 命令行参数,是一个字符串切片。
Stdin
, Stdout
, Stderr
: 标准输入、标准输出和标准错误。
3. Functions
Chdir(dir string) error
: 改变当前工作目录。
err := os.Chdir("/path/to/directory")
Chmod(name string, mode FileMode) error
: 改变文件权限。
err := os.Chmod("/path/to/file", 0644)
Chown(name string, uid, gid int) error
: 改变文件所有者。
err := os.Chown("/path/to/file", 1000, 1000)
Chtimes(name string, atime time.Time, mtime time.Time) error
: 改变文件访问和修改时间。
err := os.Chtimes("/path/to/file", time.Now(), time.Now())
Clearenv()
: 清空当前进程的环境变量。
DirFS(dir string) fs.FS
: 创建一个基于目录的文件系统。
fs := os.DirFS("/path/to/directory")
Environ() []string
: 返回当前进程的环境变量。
env := os.Environ()
Executable() (string, error)
: 返回可执行文件的路径。
exePath, err := os.Executable()
Exit(code int)
: 终止程序的执行,参数是退出码。
os.Exit(0)
Expand(s string, mapping func(string) string) string
: 根据 mapping 函数扩展字符串 s。
expanded := os.Expand("$HOME/path", func(key string) string {
return "/user/" + key
})
ExpandEnv(s string) string
: 扩展字符串 s 中的环境变量。
expanded := os.ExpandEnv("$HOME/path")
Getegid() int
, Getenv(key string) string
, Geteuid() int
, Getgid() int
, Getgroups() ([]int, error)
: 获取进程的组 ID、环境变量、用户 ID、组 ID、附属组 ID 等信息。
Getpagesize() int
: 返回底层系统内存页面的大小。
Getpid() int
, Getppid() int
: 获取进程的 ID 和父进程的 ID。
Continuing with the explanation of additional functions in the os
package:
Getuid() int
: 获取进程的用户 ID。
uid := os.Getuid()
Getwd() (dir string, err error)
: 获取当前工作目录。
dir, err := os.Getwd()
Hostname() (name string, err error)
: 获取主机名。
name, err := os.Hostname()
IsExist(err error) bool
: 判断错误是否表示文件已存在。
if os.IsExist(err) {
// File already exists
}
IsNotExist(err error) bool
: 判断错误是否表示文件或目录不存在。
if os.IsNotExist(err) {
// File or directory does not exist
}
IsPathSeparator(c uint8) bool
: 判断字符是否为路径分隔符。
if os.IsPathSeparator('/') {
// Character is a path separator
}
IsPermission(err error) bool
: 判断错误是否表示权限问题。
if os.IsPermission(err) {
// Permission issue
}
IsTimeout(err error) bool
: 判断错误是否表示超时。
if os.IsTimeout(err) {
// Timeout occurred
}
Lchown(name string, uid, gid int) error
: 改变符号链接的所有者。
err := os.Lchown("/path/to/symlink", 1000, 1000)
Link(oldname, newname string) error
: 创建硬链接。
err := os.Link("/path/to/oldfile", "/path/to/newfile")
LookupEnv(key string) (string, bool)
: 获取环境变量的值和是否存在。
value, exists := os.LookupEnv("MY_VARIABLE")
Mkdir(name string, perm FileMode) error
: 创建单层目录。
err := os.Mkdir("/path/to/directory", 0755)
MkdirAll(path string, perm FileMode) error
: 创建多层目录,如果父目录不存在也会创建。
err := os.MkdirAll("/path/to/nested/directory", 0755)
MkdirTemp(dir, pattern string) (string, error)
: 在指定目录创建一个临时目录,并返回其路径。
tempDir, err := os.MkdirTemp("/path/to", "prefix-*")
NewSyscallError(syscall string, err error) error
: 创建一个带有系统调用名称的错误。
syscallErr := os.NewSyscallError("syscallName", errors.New("error message"))
Pipe() (r *File, w *File, err error)
: 创建一个管道,返回读取和写入两个文件描述符。
r, w, err := os.Pipe()
ReadFile(name string) ([]byte, error)
: 读取文件的内容。
content, err := os.ReadFile("/path/to/file")
Readlink(name string) (string, error)
: 读取符号链接的目标路径。
target, err := os.Readlink("/path/to/symlink")
Remove(name string) error
: 删除文件或空目录。
err := os.Remove("/path/to/file")
RemoveAll(path string) error
: 递归删除目录及其子目录和文件。
err := os.RemoveAll("/path/to/directory")
Rename(oldpath, newpath string) error
: 重命名文件或目录。
err := os.Rename("/path/to/oldfile", "/path/to/newfile")
SameFile(fi1, fi2 FileInfo) bool
: 判断两个文件信息是否引用同一文件。
file1, _ := os.Stat("/path/to/file1")
file2, _ := os.Stat("/path/to/file2")
sameFile := os.SameFile(file1, file2)
Setenv(key, value string) error
: 设置环境变量。
err := os.Setenv("MY_VARIABLE", "value")
Symlink(oldname, newname string) error
: 创建符号链接。
err := os.Symlink("/path/to/target", "/path/to/symlink")
TempDir() string
: 返回用于临时文件的默认目录。
tempDir := os.TempDir()
Truncate(name string, size int64) error
: 截断文件到指定大小。
err := os.Truncate("/path/to/file", 1000)
Unsetenv(key string) error
: 移除环境变量。
err := os.Unsetenv("MY_VARIABLE")
UserCacheDir() (string, error)
: 返回用户缓存目录。
cacheDir, err := os.UserCacheDir()
UserConfigDir() (string, error)
: 返回用户配置目录。
configDir, err := os.UserConfigDir()
UserHomeDir() (string, error)
: 返回用户主目录。
homeDir, err := os.UserHomeDir()
WriteFile(name string, data []byte, perm FileMode) error
: 将数据写入文件。
err := os.WriteFile("/path/to/file", []byte("content"), 0644)
Type: DirEntry
DirEntry
表示目录中的一个条目,它包含目录项的基本信息。
entries, _ := os.ReadDir("/path/to/directory")
for _, entry := range entries {
fmt.Println(entry.Name())
}
ReadDir(name string) ([]DirEntry, error)
: 读取目录的内容,返回一个 DirEntry
切片。
entries, err := os.ReadDir("/path/to/directory")
Type: File
File
类型表示打开的文件对象,提供了对文件的各种操作和属性访问。
Create(name string) (*File, error)
: 创建或截断文件,并返回一个文件对象。
file, err := os.Create("/path/to/file.txt")
CreateTemp(dir, pattern string) (*File, error)
: 在指定目录创建临时文件,并返回一个文件对象。
file, err := os.CreateTemp("/path/to", "prefix-*.txt")
NewFile(fd uintptr, name string) *File
: 使用文件描述符创建文件对象。
file := os.NewFile(3, "/path/to/file")
Open(name string) (*File, error)
: 打开文件并返回一个文件对象。
file, err := os.Open("/path/to/file.txt")
OpenFile(name string, flag int, perm FileMode) (*File, error)
: 打开文件或创建文件对象,支持更多的选项。
file, err := os.OpenFile("/path/to/file.txt", os.O_RDWR|os.O_CREATE, 0644)
Chdir() error
: 改变当前工作目录到文件所在目录。
file, _ := os.Open("/path/to/file.txt")
err := file.Chdir()
Chmod(mode FileMode) error
: 改变文件权限。
file, _ := os.Open("/path/to/file.txt")
err := file.Chmod(0644)
Chown(uid, gid int) error
: 改变文件所有者。
file, _ := os.Open("/path/to/file.txt")
err := file.Chown(1000, 1000)
Close() error
: 关闭文件。
file, _ := os.Open("/path/to/file.txt")
err := file.Close()
Fd() uintptr
: 返回文件的底层文件描述符。
file, _ := os.Open("/path/to/file.txt")
fd := file.Fd()
Name() string
: 返回文件的名称。
file, _ := os.Open("/path/to/file.txt")
name := file.Name()
Read(b []byte) (n int, err error)
: 读取文件内容到指定字节切片。
file, _ := os.Open("/path/to/file.txt")
buffer := make([]byte, 1024)
n, err := file.Read(buffer)
ReadAt(b []byte, off int64) (n int, err error)
: 从指定偏移位置读取文件内容到字节切片。
file, _ := os.Open("/path/to/file.txt")
buffer := make([]byte, 1024)
n, err := file.ReadAt(buffer, 0)
ReadDir(n int) ([]DirEntry, error)
: 读取目录内容,返回 DirEntry
切片。
dir, _ := os.Open("/path/to/directory")
entries, err := dir.ReadDir(10)
ReadFrom(r io.Reader) (n int64, err error)
: 从 io.Reader
接口读取数据到文件。
file, _ := os.Create("/path/to/file.txt")
reader := strings.NewReader("content")
n, err := file.ReadFrom(reader)
Readdir(n int) ([]FileInfo, error)
: 读取目录内容,返回 FileInfo
切片。
dir, _ := os.Open("/path/to/directory")
fileInfos, err := dir.Readdir(10)
Readdirnames(n int) (names []string, err error)
: 读取目录内容,返回文件名切片。
dir, _ := os.Open("/path/to/directory")
names, err := dir.Readdirnames(10)
Seek(offset int64, whence int) (ret int64, err error)
: 移动文件指针到指定位置。
file, _ := os.Open("/path/to/file.txt")
offset := int64(10)
ret, err := file.Seek(offset, io.SeekStart)
SetDeadline(t time.Time) error
: 设置文件的读写截止时间。
file, _ := os.Open("/path/to/file.txt")
deadline := time.Now().Add(10 * time.Second)
err := file.SetDeadline(deadline)
SetReadDeadline(t time.Time) error
: 设置文件的读截止时间。
file, _ := os.Open("/path/to/file.txt")
deadline := time.Now().Add(10 * time.Second)
err := file.SetReadDeadline(deadline)
SetWriteDeadline(t time.Time) error
: 设置文件的写截止时间。
file, _ := os.Open("/path/to/file.txt")
deadline := time.Now().Add(10 * time.Second)
err := file.SetWriteDeadline(deadline)
Stat() (FileInfo, error)
: 获取文件信息。
file, _ := os.Open("/path/to/file.txt")
fileInfo, err := file.Stat()
Sync() error
: 将文件内容同步到稳定存储。
file, _ := os.OpenFile("/path/to/file.txt", os.O_RDWR, 0644)
err := file.Sync()
SyscallConn() (syscall.RawConn, error)
: 返回与文件关联的原始连接。
file, _ := os.Open("/path/to/file.txt")
rawConn, err := file.SyscallConn()
Truncate(size int64) error
: 截断文件到指定大小。
file, _ := os.OpenFile("/path/to/file.txt", os.O_RDWR, 0644)
err := file.Truncate(1000)
Write(b []byte) (n int, err error)
: 将字节切片写入文件。
file, _ := os.OpenFile("/path/to/file.txt", os.O_WRONLY, 0644)
n, err := file.Write([]byte("content"))
WriteAt(b []byte, off int64) (n int, err error)
: 从指定偏移位置开始写入字节切片。
file, _ := os.OpenFile("/path/to/file.txt", os.O_WRONLY, 0644)
n, err := file.WriteAt([]byte("content"), 10)
WriteString(s string) (n int, err error)
: 将字符串写入文件。
file, _ := os.OpenFile("/path/to/file.txt", os.O_WRONLY, 0644)
n, err := file.WriteString("content")
Type: FileInfo
FileInfo
表示文件的元信息,可以通过文件对象的 Stat
或 Lstat
方法获取。
Lstat(name string) (FileInfo, error)
: 返回一个文件的元信息,不跟随符号链接。
fileInfo, err := os.Lstat("/path/to/file.txt")
Stat(name string) (FileInfo, error)
: 返回一个文件的元信息,会跟随符号链接。
fileInfo, err := os.Stat("/path/to/file.txt")
Mode() FileMode
: 返回文件的权限和模式。
mode := fileInfo.Mode()
Name() string
: 返回文件或目录的名称。
name := fileInfo.Name()
Size() int64
: 返回文件的大小。
size := fileInfo.Size()
IsDir() bool
: 判断是否为目录。
isDir := fileInfo.IsDir()
ModTime() time.Time
: 返回文件的修改时间。
modTime := fileInfo.ModTime()
Sys() interface{}
: 返回底层数据的平台特定表示。
sys := fileInfo.Sys()
Type: FileMode
FileMode
表示文件的权限和模式。
Perm() FileMode
: 返回文件的权限部分。
fileMode := FileMode.Perm()
String() string
: 返回表示文件模式的字符串。
modeString := fileMode.String()
Type: LinkError
LinkError
表示与创建或解析符号链接相关的错误。
Error() string
: 返回错误的字符串表示。
linkErr := &LinkError{Op: "operation", Old: "/old/path", New: "/new/path", Err: errors.New("error message")}
errString := linkErr.Error()
Unwrap() error
: 返回底层错误。
underlyingErr := linkErr.Unwrap()
Type: PathError
PathError
表示与文件路径相关的错误。
Error() string
: 返回错误的字符串表示。
pathErr := &PathError{Op: "operation", Path: "/file/path", Err: errors.New("error message")}
errString := pathErr.Error()
Unwrap() error
: 返回底层错误。
underlyingErr := pathErr.Unwrap()
Type: ProcAttr
ProcAttr
表示一个新进程的属性。
该类型包含了新进程的环境变量、文件描述符、工作目录等信息。
Type: Process
Process
表示一个正在运行的进程。
FindProcess(pid int) (*Process, error)
: 根据进程ID查找并返回一个 Process
对象。
process, err := os.FindProcess(12345)
StartProcess(name string, argv []string, attr *ProcAttr) (*Process, error)
: 启动一个新进程并返回一个 Process
对象。
process, err := os.StartProcess("/path/to/executable", []string{"arg1", "arg2"}, &os.ProcAttr{})
(p *Process) Kill() error
: 终止进程。
err := process.Kill()
(p *Process) Release() error
: 释放与 Process
对象关联的资源。
err := process.Release()
(p *Process) Signal(sig Signal) error
: 向进程发送信号。
err := process.Signal(os.Interrupt)
(p *Process) Wait() (*ProcessState, error)
: 等待进程结束并返回 ProcessState
对象。
state, err := process.Wait()
Type: ProcessState
ProcessState
表示一个进程的状态信息。
(p *ProcessState) ExitCode() int
: 返回进程的退出码。
exitCode := state.ExitCode()
(p *ProcessState) Exited() bool
: 判断进程是否已经退出。
hasExited := state.Exited()
(p *ProcessState) Pid() int
: 返回进程的进程ID。
pid := state.Pid()
(p *ProcessState) String() string
: 返回进程状态的字符串表示。
stateString := state.String()
(p *ProcessState) Success() bool
: 判断进程是否成功退出。
isSuccess := state.Success()
(p *ProcessState) Sys() any
: 返回底层数据的平台特定表示。
sysData := state.Sys()
(p *ProcessState) SysUsage() any
: 返回与进程相关的系统资源使用信息。
sysUsage := state.SysUsage()
(p *ProcessState) SystemTime() time.Duration
: 返回进程的系统时间。
systemTime := state.SystemTime()
(p *ProcessState) UserTime() time.Duration
: 返回进程的用户时间。
userTime := state.UserTime()
Type: Signal
Signal
表示一个操作系统的信号。
常用的信号包括 Interrupt
、Kill
、Hangup
等。
Type: SyscallError
SyscallError
表示与系统调用相关的错误。
Error() string
: 返回错误的字符串表示。
syscallErr := &SyscallError{Syscall: "syscall", Err: errors.New("error message")}
errString := syscallErr.Error()
Timeout() bool
: 判断错误是否与超时相关。
isTimeout := syscallErr.Timeout()
Unwrap() error
: 返回底层错误。
underlyingErr := syscallErr.Unwrap()