package os
import "os"
Package os 为操作系统功能提供与平台无关的接口。 其设计类似 Unix,不过错误处理是 Go 风格的; 失败的调用返回 error 类型的值,而不是错误编号。 通常,错误中会包含更多信息。例如, 如果接受文件名的调用失败,如 Open 或 Stat,打印时错误中 会包含导致失败的文件名,且其类型为 *PathError,可以对其进行解包以获取更多信息。
os 接口旨在跨所有操作系统保持统一。 并非普遍可用的功能出现在特定于系统的 syscall 包中。
下面是一个简单示例,打开一个文件并读取其中一部分。
file, err := os.Open("file.go") // 用于读取访问。
if err != nil {
log.Fatal(err)
}
如果打开失败,错误字符串会不言自明,例如
open file.go: no such file or directory
随后可以将文件的数据读入一个字节切片。Read 和 Write 从参数切片的长度获取其字节数。
data := make([]byte, 100)
count, err := file.Read(data)
if err != nil {
log.Fatal(err)
}
fmt.Printf("read %d bytes: %q\n", count, data[:count])
并发
File 的方法对应文件系统操作。所有方法都 可安全并发使用。一个 File 上的最大并发 操作数可能受操作系统或系统限制。这个 数字应该很高,但超过它可能会降低性能或导致其他问题。
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 Clearenv()
- func CopyFS(dir string, fsys fs.FS) error
- func DirFS(dir string) fs.FS
- func Environ() []string
- func Executable() (string, error)
- func Exit(code int)
- func Expand(s string, mapping func(string) string) string
- func ExpandEnv(s string) string
- func Getegid() int
- func Getenv(key string) string
- func Geteuid() int
- func Getgid() int
- func Getgroups() ([]int, error)
- func Getpagesize() int
- func Getpid() int
- func Getppid() int
- func Getuid() int
- func Getwd() (dir string, err error)
- func Hostname() (name string, err error)
- func IsExist(err error) bool
- func IsNotExist(err error) bool
- func IsPathSeparator(c uint8) bool
- func IsPermission(err error) bool
- func IsTimeout(err error) bool
- 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 MkdirAll(path string, perm FileMode) error
- func MkdirTemp(dir, pattern string) (string, error)
- func NewSyscallError(syscall string, err error) error
- func Pipe() (r *File, w *File, err error)
- func ReadFile(name string) ([]byte, error)
- func Readlink(name string) (string, error)
- func Remove(name string) error
- func RemoveAll(path 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 UserCacheDir() (string, error)
- func UserConfigDir() (string, error)
- func UserHomeDir() (string, error)
- func WriteFile(name string, data []byte, perm FileMode) error
- type DirEntry
-
type File
- func Create(name string) (*File, error)
- func CreateTemp(dir, pattern string) (*File, error)
- func NewFile(fd uintptr, name string) *File
- func Open(name string) (*File, error)
- func OpenFile(name string, flag int, perm FileMode) (*File, error)
- func OpenInRoot(dir, name string) (*File, error)
- func (f *File) Chdir() error
- func (f *File) Chmod(mode FileMode) error
- func (f *File) Chown(uid, gid int) error
- func (f *File) Close() error
- func (f *File) Fd() uintptr
- func (f *File) Name() string
- func (f *File) Read(b []byte) (n int, err error)
- func (f *File) ReadAt(b []byte, off int64) (n int, err error)
- func (f *File) ReadDir(n int) ([]DirEntry, error)
- func (f *File) ReadFrom(r io.Reader) (n int64, err error)
- func (f *File) Readdir(n int) ([]FileInfo, error)
- func (f *File) Readdirnames(n int) (names []string, err error)
- func (f *File) Seek(offset int64, whence int) (ret int64, err error)
- func (f *File) SetDeadline(t time.Time) error
- func (f *File) SetReadDeadline(t time.Time) error
- func (f *File) SetWriteDeadline(t time.Time) error
- func (f *File) Stat() (FileInfo, error)
- func (f *File) Sync() error
- func (f *File) SyscallConn() (syscall.RawConn, error)
- func (f *File) Truncate(size int64) error
- func (f *File) Write(b []byte) (n int, err error)
- func (f *File) WriteAt(b []byte, off int64) (n int, err error)
- func (f *File) WriteString(s string) (n int, err error)
- func (f *File) WriteTo(w io.Writer) (n int64, err error)
- type FileInfo
- type FileMode
- type LinkError
- type PathError
- type ProcAttr
-
type Process
- func FindProcess(pid int) (*Process, error)
- func StartProcess(name string, argv []string, attr *ProcAttr) (*Process, error)
- func (p *Process) Kill() error
- func (p *Process) Release() error
- func (p *Process) Signal(sig Signal) error
- func (p *Process) Wait() (*ProcessState, error)
- func (p *Process) WithHandle(f func(handle uintptr)) error
-
type ProcessState
- func (p *ProcessState) ExitCode() int
- func (p *ProcessState) Exited() bool
- func (p *ProcessState) Pid() int
- func (p *ProcessState) String() string
- func (p *ProcessState) Success() bool
- func (p *ProcessState) Sys() any
- func (p *ProcessState) SysUsage() any
- func (p *ProcessState) SystemTime() time.Duration
- func (p *ProcessState) UserTime() time.Duration
-
type Root
- func OpenRoot(name string) (*Root, error)
- func (r *Root) Chmod(name string, mode FileMode) error
- func (r *Root) Chown(name string, uid, gid int) error
- func (r *Root) Chtimes(name string, atime time.Time, mtime time.Time) error
- func (r *Root) Close() error
- func (r *Root) Create(name string) (*File, error)
- func (r *Root) FS() fs.FS
- func (r *Root) Lchown(name string, uid, gid int) error
- func (r *Root) Link(oldname, newname string) error
- func (r *Root) Lstat(name string) (FileInfo, error)
- func (r *Root) Mkdir(name string, perm FileMode) error
- func (r *Root) MkdirAll(name string, perm FileMode) error
- func (r *Root) Name() string
- func (r *Root) Open(name string) (*File, error)
- func (r *Root) OpenFile(name string, flag int, perm FileMode) (*File, error)
- func (r *Root) OpenRoot(name string) (*Root, error)
- func (r *Root) ReadFile(name string) ([]byte, error)
- func (r *Root) Readlink(name string) (string, error)
- func (r *Root) Remove(name string) error
- func (r *Root) RemoveAll(name string) error
- func (r *Root) Rename(oldname, newname string) error
- func (r *Root) Stat(name string) (FileInfo, error)
- func (r *Root) Symlink(oldname, newname string) error
- func (r *Root) WriteFile(name string, data []byte, perm FileMode) error
- type Signal
- type SyscallError
Examples
- Chmod
- Chtimes
- CreateTemp
- CreateTemp (Suffix)
- Expand
- ExpandEnv
- FileMode
- Getenv
- LookupEnv
- Mkdir
- MkdirAll
- MkdirTemp
- MkdirTemp (Suffix)
- OpenFile
- OpenFile (Append)
- ReadDir
- ReadFile
- Readlink
- Unsetenv
- UserCacheDir
- UserConfigDir
- WriteFile
Constants
const ( // 必须指定 O_RDONLY、O_WRONLY 或 O_RDWR 中的恰好一个。 O_RDONLY int = syscall.O_RDONLY // 以只读方式打开文件。 O_WRONLY int = syscall.O_WRONLY // 以只写方式打开文件。 O_RDWR int = syscall.O_RDWR // 以读写方式打开文件。 // 其余的值可以按位或进来以控制行为。 O_APPEND int = syscall.O_APPEND // 写入时向文件追加数据。 O_CREATE int = syscall.O_CREAT // 如果文件不存在则创建新文件。 O_EXCL int = syscall.O_EXCL // 与 O_CREATE 一起使用,文件必须不存在。 O_SYNC int = syscall.O_SYNC // 以同步 I/O 方式打开。 O_TRUNC int = syscall.O_TRUNC // 打开时截断常规可写文件。 )
OpenFile 的标志,对底层系统的标志进行了封装。 并非所有标志都在给定的系统上实现。
const ( SEEK_SET int = 0 // 相对于文件起始位置 seek SEEK_CUR int = 1 // 相对于当前偏移量 seek SEEK_END int = 2 // 相对于末尾 seek )
Seek 的 whence 值。
Deprecated: 请使用 io.SeekStart、io.SeekCurrent 和 io.SeekEnd。
const ( PathSeparator = '/' // 特定于操作系统的路径分隔符 PathListSeparator = ':' // 特定于操作系统的路径列表分隔符 )
const ( // 单个字母是 String 方法格式化时 // 使用的缩写。 ModeDir = fs.ModeDir // d: 是一个目录 ModeAppend = fs.ModeAppend // a: 仅追加 ModeExclusive = fs.ModeExclusive // l: 独占使用 ModeTemporary = fs.ModeTemporary // T: 临时文件;仅 Plan 9 ModeSymlink = fs.ModeSymlink // L: 符号链接 ModeDevice = fs.ModeDevice // D: 设备文件 ModeNamedPipe = fs.ModeNamedPipe // p: 命名管道(FIFO) ModeSocket = fs.ModeSocket // S: Unix 域套接字 ModeSetuid = fs.ModeSetuid // u: setuid ModeSetgid = fs.ModeSetgid // g: setgid ModeCharDevice = fs.ModeCharDevice // c: Unix 字符设备,当设置了 ModeDevice 时 ModeSticky = fs.ModeSticky // t: sticky ModeIrregular = fs.ModeIrregular // ?: 非常规文件;关于此文件没有其他已知信息 // 类型位的掩码。对于常规文件,不会设置任何位。 ModeType = fs.ModeType ModePerm = fs.ModePerm // Unix 权限位,0o777 )
定义的文件模式位是 FileMode 的最高有效位。 九个最低有效位是标准的 Unix rwxrwxrwx 权限。 这些位的值应被视为公共 API 的一部分, 可能会用于线协议或磁盘表示:它们不得 被更改,尽管可能会新增一些位。
const DevNull = "/dev/null"
DevNull 是操作系统 “空设备” 的名称。 在类 Unix 系统上,它是 "/dev/null";在 Windows 上,是 "NUL"。
Variables
var ( // ErrInvalid 表示参数无效。 // 当接收者为 nil 时,File 上的方法将返回此错误。 ErrInvalid = fs.ErrInvalid // "invalid argument" ErrPermission = fs.ErrPermission // "permission denied" ErrExist = fs.ErrExist // "file already exists" ErrNotExist = fs.ErrNotExist // "file does not exist" ErrClosed = fs.ErrClosed // "file already closed" ErrNoDeadline = errNoDeadline() // "file type does not support deadline" ErrDeadlineExceeded = errDeadlineExceeded() // "i/o timeout" )
一些常见系统调用错误的可移植对应物。
从此包返回的错误可以用 errors.Is 针对这些错误进行测试。
var ( // ErrProcessDone 表示一个 [Process] 已完成。 ErrProcessDone = errors.New("os: process already finished") // ErrNoHandle 表示一个 [Process] 没有句柄。 ErrNoHandle = errors.New("os: process handle unavailable") )
var ( Stdin = NewFile(uintptr(syscall.Stdin), "/dev/stdin") Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout") Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr") )
Stdin、Stdout 和 Stderr 是指向标准输入、 标准输出和标准错误文件描述符的已打开的 File。
注意,Go 运行时在发生 panic 和崩溃时会写入标准错误; 关闭 Stderr 可能导致这些消息被写到别处, 也许会写到之后打开的文件中。
var Args []string
Args 保存命令行参数,以程序名开头。
Functions
func Chdir
func Chdir(dir string) error
Chdir 将当前工作目录更改为指定的目录。 如果出错,错误的类型为 *PathError。
func Chmod
func Chmod(name string, mode FileMode) error
Chmod 将指定文件的模式更改为 mode。 如果文件是符号链接,它会更改链接目标的模式。 如果出错,错误的类型为 *PathError。
根据操作系统的不同,会使用模式位的不同子集。
在 Unix 上,使用模式的权限位、ModeSetuid、ModeSetgid 和 ModeSticky。
在 Windows 上,只使用模式的 0o200 位(属主可写); 它控制文件的只读属性是被设置还是被清除。 其他位目前未使用。为了与 Go 1.12 及更早版本兼容,请使用非零的 mode。对只读 文件使用模式 0o400,对可读可写文件使用 0o600。
在 Plan 9 上,使用模式的权限位、ModeAppend、ModeExclusive
和 ModeTemporary。
Example
package main
import (
"log"
"os"
)
func main() {
if err := os.Chmod("some-filename", 0644); err != nil {
log.Fatal(err)
}
}
func Chown
func Chown(name string, uid, gid int) error
Chown 更改指定文件的数字 uid 和 gid。 如果文件是符号链接,它会更改链接目标的 uid 和 gid。 uid 或 gid 为 -1 表示不更改该值。 如果出错,错误的类型为 *PathError。
在 Windows 或 Plan 9 上,Chown 总是返回 syscall.EWINDOWS 或 syscall.EPLAN9 错误,并包装在 *PathError 中。
func Chtimes
func Chtimes(name string, atime time.Time, mtime time.Time) error
Chtimes 更改指定文件的访问时间和修改时间, 类似于 Unix 的 utime() 或 utimes() 函数。 零值 time.Time 将使对应的文件时间保持不变。
底层文件系统可能会将值截断或舍入为
精度更低的时间单位。
如果出错,错误的类型为 *PathError。
Example
package main
import (
"log"
"os"
"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 {
log.Fatal(err)
}
}
func Clearenv
func Clearenv()
Clearenv 删除所有环境变量。
func CopyFS
func CopyFS(dir string, fsys fs.FS) error
CopyFS 将文件系统 fsys 复制到目录 dir 中, 必要时创建 dir。
文件以模式 0o666 加上源中的任何执行权限创建, 目录以模式 0o777 创建(在应用 umask 之前)。
CopyFS 不会覆盖已存在的文件。如果 fsys 中的某个文件名 已存在于目标中,CopyFS 将返回一个错误, 使得 errors.Is(err, fs.ErrExist) 为 true。
dir 中的符号链接会被跟随。
在 CopyFS 运行期间添加到 fsys 的新文件 (包括 dir 是 fsys 的子目录的情况)不保证会被复制。
复制在遇到第一个错误时停止并返回该错误。
func DirFS
func DirFS(dir string) fs.FS
DirFS 返回一个文件系统(fs.FS),其根目录是以 dir 为根的目录树。
请注意,DirFS("/prefix") 只保证它向操作系统发起的 Open 调用 会以 "/prefix" 开头:DirFS("/prefix").Open("file") 等同于 os.Open("/prefix/file")。因此,如果 /prefix/file 是一个指向 /prefix 树 之外的符号链接,那么使用 DirFS 并不会比使用 os.Open 更能阻止访问。此外,对于相对路径 DirFS("prefix") 返回的 fs.FS 的根 会受到之后调用 Chdir 的影响。因此,当目录树 包含任意内容时,DirFS 并不是 chroot 式安全机制的通用替代品。
使用 Root.FS 来获取一个能防止通过符号链接逃逸出树的 fs.FS。
dir 目录不能为 ""。
结果实现了 io/fs.StatFS、io/fs.ReadFileFS、io/fs.ReadDirFS 和 io/fs.ReadLinkFS。
func Environ
func Environ() []string
Environ 返回表示环境的字符串副本, 形式为 "key=value"。
func Executable
func Executable() (string, error)
Executable 返回启动当前进程的可执行文件的路径名。 不保证该路径仍指向正确的可执行文件。如果使用符号链接 启动进程,取决于操作系统,结果可能是符号链接 或其指向的路径。如果需要稳定的结果, path/filepath.EvalSymlinks 可能有帮助。
除非发生错误,Executable 返回绝对路径。
主要用例是查找相对于可执行文件位置的资源。
func Exit
func Exit(code int)
Exit 使当前程序以给定的状态码退出。 按惯例,状态码 0 表示成功,非零表示错误。 程序会立即终止;deferred 函数不会运行。
为便于移植,状态码应在 [0, 125] 范围内。
func Expand
func Expand(s string, mapping func(string) string) string
Expand 根据映射函数替换字符串中的 ${var} 或 $var。
例如,os.ExpandEnv(s) 等价于 os.Expand(s, os.Getenv)。
Output:Example
package main
import (
"fmt"
"os"
)
func main() {
mapper := func(placeholderName string) string {
switch placeholderName {
case "DAY_PART":
return "morning"
case "NAME":
return "Gopher"
}
return ""
}
fmt.Println(os.Expand("Good ${DAY_PART}, $NAME!", mapper))
}
Good morning, Gopher!
func ExpandEnv
func ExpandEnv(s string) string
ExpandEnv 根据当前环境变量的值替换字符串中的 ${var} 或 $var。
对未定义变量的引用会被替换为空字符串。
Output:Example
package main
import (
"fmt"
"os"
)
func main() {
os.Setenv("NAME", "gopher")
os.Setenv("BURROW", "/usr/gopher")
fmt.Println(os.ExpandEnv("$NAME lives in ${BURROW}."))
}
gopher lives in /usr/gopher.
func Getegid
func Getegid() int
Getegid 返回调用者的有效数字组 ID。
在 Windows 上,它返回 -1。
func Getenv
func Getenv(key string) string
Getenv 检索由 key 命名的环境变量的值。
它返回该值,如果变量不存在则为空。
要区分空值和未设置的值,请使用 LookupEnv。
Output:Example
package main
import (
"fmt"
"os"
)
func main() {
os.Setenv("NAME", "gopher")
os.Setenv("BURROW", "/usr/gopher")
fmt.Printf("%s lives in %s.\n", os.Getenv("NAME"), os.Getenv("BURROW"))
}
gopher lives in /usr/gopher.
func Geteuid
func Geteuid() int
Geteuid 返回调用者的有效数字用户 ID。
在 Windows 上,它返回 -1。
func Getgid
func Getgid() int
Getgid 返回调用者的数字组 ID。
在 Windows 上,它返回 -1。
func Getgroups
func Getgroups() ([]int, error)
Getgroups 返回调用者所属组的数字 ID 列表。
在 Windows 上,它返回 syscall.EWINDOWS。有关可能的替代方案, 参见 os/user 包。
func Getpagesize
func Getpagesize() int
Getpagesize 返回底层系统的内存页大小。
func Getpid
func Getpid() int
Getpid 返回调用者的进程 id。
func Getppid
func Getppid() int
Getppid 返回调用者父进程的进程 id。
func Getuid
func Getuid() int
Getuid 返回调用者的数字用户 ID。
在 Windows 上,它返回 -1。
func Getwd
func Getwd() (dir string, err error)
Getwd 返回对应当前目录的绝对路径名。 如果当前目录可以通过多条路径到达 (由于符号链接),Getwd 可能返回其中任意一条。
在 Unix 平台上,如果环境变量 PWD 提供了绝对名称,且它是当前目录的名称, 则返回它。
func Hostname
func Hostname() (name string, err error)
Hostname 返回内核报告的主机名。
func IsExist
func IsExist(err error) bool
IsExist 返回一个布尔值,指示其参数是否已知报告 文件或目录已存在。它可由 ErrExist 以及 某些系统调用错误满足。
此函数早于 errors.Is。它仅支持由 os 包返回的错误。 新代码应使用 errors.Is(err, fs.ErrExist)。
func IsNotExist
func IsNotExist(err error) bool
IsNotExist 返回一个布尔值,指示其参数是否已知 报告文件或目录不存在。它可由 ErrNotExist 以及某些系统调用错误满足。
此函数早于 errors.Is。它仅支持由 os 包返回的错误。 新代码应使用 errors.Is(err, fs.ErrNotExist)。
func IsPathSeparator
func IsPathSeparator(c uint8) bool
IsPathSeparator 报告 c 是否为目录分隔符字符。
func IsPermission
func IsPermission(err error) bool
IsPermission 返回一个布尔值,指示其参数是否已知 报告权限被拒绝。它可由 ErrPermission 以及 某些系统调用错误满足。
此函数早于 errors.Is。它仅支持由 os 包返回的错误。 新代码应使用 errors.Is(err, fs.ErrPermission)。
func IsTimeout
func IsTimeout(err error) bool
IsTimeout 返回一个布尔值,指示其参数是否已知 报告发生了超时。
此函数早于 errors.Is,并且错误是否表示超时的概念 可能含糊不清。例如,Unix 错误 EWOULDBLOCK 有时表示超时,有时不表示。 新代码应使用 errors.Is,并传入适合返回该错误的调用 的值,例如 os.ErrDeadlineExceeded。
func Lchown
func Lchown(name string, uid, gid int) error
Lchown 更改指定文件的数字 uid 和 gid。 如果文件是符号链接,它会更改链接本身的 uid 和 gid。 如果出错,错误的类型为 *PathError。
在 Windows 上,它总是返回 syscall.EWINDOWS 错误, 并包装在 *PathError 中。
func Link
func Link(oldname, newname string) error
Link 将 newname 创建为指向 oldname 文件的硬链接。 如果出错,错误的类型为 *LinkError。
func LookupEnv
func LookupEnv(key string) (string, bool)
LookupEnv 检索由 key 命名的环境变量的值。
如果变量存在于环境中,则返回值(可能为空)且布尔值为 true。
否则,返回值将为空且布尔值为 false。
Output:Example
package main
import (
"fmt"
"os"
)
func main() {
show := func(key string) {
val, ok := os.LookupEnv(key)
if !ok {
fmt.Printf("%s not set\n", key)
} else {
fmt.Printf("%s=%s\n", key, val)
}
}
os.Setenv("SOME_KEY", "value")
os.Setenv("EMPTY_KEY", "")
show("SOME_KEY")
show("EMPTY_KEY")
show("MISSING_KEY")
}
SOME_KEY=value
EMPTY_KEY=
MISSING_KEY not set
func Mkdir
func Mkdir(name string, perm FileMode) error
Mkdir 使用指定的名称和权限位(在 umask 之前)创建一个新目录。
如果出错,错误的类型为 *PathError。
Example
package main
import (
"log"
"os"
)
func main() {
err := os.Mkdir("testdir", 0750)
if err != nil && !os.IsExist(err) {
log.Fatal(err)
}
err = os.WriteFile("testdir/testfile.txt", []byte("Hello, Gophers!"), 0660)
if err != nil {
log.Fatal(err)
}
}
func MkdirAll
func MkdirAll(path string, perm FileMode) error
MkdirAll 创建一个名为 path 的目录,
以及任何必要的父目录,并返回 nil,
否则返回错误。
权限位 perm(在 umask 之前)用于 MkdirAll
创建的所有目录。
如果 path 已经是一个目录,MkdirAll 什么都不做
并返回 nil。
Example
package main
import (
"log"
"os"
)
func main() {
err := os.MkdirAll("test/subdir", 0750)
if err != nil {
log.Fatal(err)
}
err = os.WriteFile("test/subdir/testfile.txt", []byte("Hello, Gophers!"), 0660)
if err != nil {
log.Fatal(err)
}
}
func MkdirTemp
func MkdirTemp(dir, pattern string) (string, error)
MkdirTemp 在目录 dir 中创建一个新的临时目录,
并返回新目录的路径名。
新目录的名称通过在 pattern 末尾追加一个随机字符串生成。
如果 pattern 中包含 "*",则随机字符串会替换最后一个 "*"。
目录以模式 0o700(受 umask 影响之前)创建。
如果 dir 为空字符串,MkdirTemp 使用 TempDir 返回的默认临时文件目录。
多个程序或 goroutine 同时调用 MkdirTemp 时不会选择同一个目录。
当不再需要该目录时,删除它是调用者的责任。
Example
package main
import (
"log"
"os"
"path/filepath"
)
func main() {
dir, err := os.MkdirTemp("", "example")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(dir) // clean up
file := filepath.Join(dir, "tmpfile")
if err := os.WriteFile(file, []byte("content"), 0666); err != nil {
log.Fatal(err)
}
}
Example (Suffix)
package main
import (
"log"
"os"
"path/filepath"
)
func main() {
logsDir, err := os.MkdirTemp("", "*-logs")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(logsDir) // clean up
// Logs can be cleaned out earlier if needed by searching
// for all directories whose suffix ends in *-logs.
globPattern := filepath.Join(os.TempDir(), "*-logs")
matches, err := filepath.Glob(globPattern)
if err != nil {
log.Fatalf("Failed to match %q: %v", globPattern, err)
}
for _, match := range matches {
if err := os.RemoveAll(match); err != nil {
log.Printf("Failed to remove %q: %v", match, err)
}
}
}
func NewSyscallError
func NewSyscallError(syscall string, err error) error
NewSyscallError 返回一个新的 SyscallError 作为错误, 其中包含给定的系统调用名称和错误详情。 为方便起见,如果 err 为 nil,NewSyscallError 返回 nil。
func Pipe
func Pipe() (r *File, w *File, err error)
Pipe 返回一对相连的 File;从 r 读取到的内容正是写入 w 的字节。 如果发生错误,它会返回这些文件和该错误。
func ReadFile
func ReadFile(name string) ([]byte, error)
ReadFile 读取指定文件并返回其内容。
成功的调用返回 err == nil,而不是 err == EOF。
因为 ReadFile 读取整个文件,所以它不会将 Read 返回的 EOF
视为需要报告的错误。
Output:Example
package main
import (
"log"
"os"
)
func main() {
data, err := os.ReadFile("testdata/hello")
if err != nil {
log.Fatal(err)
}
os.Stdout.Write(data)
}
Hello, Gophers!
func Readlink
func Readlink(name string) (string, error)
Readlink 返回指定符号链接的目标。 如果出错,错误的类型为 *PathError。
如果链接目标是相对路径,Readlink 会返回相对路径,
而不会将其解析为绝对路径。
Output:Example
package main
import (
"errors"
"fmt"
"log"
"os"
"path/filepath"
)
func main() {
// First, we create a relative symlink to a file.
d, err := os.MkdirTemp("", "")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(d)
targetPath := filepath.Join(d, "hello.txt")
if err := os.WriteFile(targetPath, []byte("Hello, Gophers!"), 0644); err != nil {
log.Fatal(err)
}
linkPath := filepath.Join(d, "hello.link")
if err := os.Symlink("hello.txt", filepath.Join(d, "hello.link")); err != nil {
if errors.Is(err, errors.ErrUnsupported) {
// Allow the example to run on platforms that do not support symbolic links.
fmt.Printf("%s links to %s\n", filepath.Base(linkPath), "hello.txt")
return
}
log.Fatal(err)
}
// Readlink returns the relative path as passed to os.Symlink.
dst, err := os.Readlink(linkPath)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%s links to %s\n", filepath.Base(linkPath), dst)
var dstAbs string
if filepath.IsAbs(dst) {
dstAbs = dst
} else {
// Symlink targets are relative to the directory containing the link.
dstAbs = filepath.Join(filepath.Dir(linkPath), dst)
}
// Check that the target is correct by comparing it with os.Stat
// on the original target path.
dstInfo, err := os.Stat(dstAbs)
if err != nil {
log.Fatal(err)
}
targetInfo, err := os.Stat(targetPath)
if err != nil {
log.Fatal(err)
}
if !os.SameFile(dstInfo, targetInfo) {
log.Fatalf("link destination (%s) is not the same file as %s", dstAbs, targetPath)
}
}
hello.link links to hello.txt
func Remove
func Remove(name string) error
Remove 删除指定文件或(空)目录。 如果出错,错误的类型为 *PathError。
func RemoveAll
func RemoveAll(path string) error
RemoveAll 移除 path 及其包含的任何子项。 它会尽力移除所有内容,但会返回它遇到的 第一个错误。如果 path 不存在,RemoveAll 返回 nil(无错误)。 如果出错,错误的类型为 *PathError。
func Rename
func Rename(oldpath, newpath string) error
Rename 将 oldpath 重命名(移动)为 newpath。 如果 newpath 已存在且不是目录,Rename 会替换它。 如果 newpath 已存在且是目录,Rename 会返回错误。 当 oldpath 和 newpath 位于不同目录时,可能适用特定于操作系统的限制。 即使在同一个目录内,在非 Unix 平台上 Rename 也不是原子操作。 如果出错,错误的类型为 *LinkError。
func SameFile
func SameFile(fi1, fi2 FileInfo) bool
SameFile 报告 fi1 和 fi2 是否描述同一个文件。 例如,在 Unix 上这意味着两个底层结构的设备 和 inode 字段完全相同;在其他系统上, 判断可能基于路径名。 SameFile 仅适用于由本包的 Stat 返回的结果。 在其他情况下它返回 false。
func Setenv
func Setenv(key, value string) error
Setenv 设置由 key 命名的环境变量的值。 如果有错误,则返回该错误。
func Symlink
func Symlink(oldname, newname string) error
Symlink 将 newname 创建为指向 oldname 的符号链接。 在 Windows 上,指向不存在的 oldname 的符号链接会创建文件符号链接; 如果 oldname 之后作为目录被创建,该符号链接将无法工作。 如果出错,错误的类型为 *LinkError。
func TempDir
func TempDir() string
TempDir 返回用于临时文件的默认目录。
在 Unix 系统上,如果 $TMPDIR 非空则返回它,否则返回 /tmp。 在 Windows 上,它使用 GetTempPath,返回 %TMP%、%TEMP%、%USERPROFILE% 或 Windows 目录中第一个非空的值。 在 Plan 9 上,它返回 /tmp。
该目录既不保证存在,也不保证具有可访问的权限。
func Truncate
func Truncate(name string, size int64) error
Truncate 更改指定文件的大小。 如果文件是符号链接,它会更改链接目标的大小。 如果出错,错误的类型为 *PathError。
func Unsetenv
func Unsetenv(key string) error
Unsetenv 取消设置单个环境变量。
Example
package main
import (
"os"
)
func main() {
os.Setenv("TMPDIR", "/my/tmp")
defer os.Unsetenv("TMPDIR")
}
func UserCacheDir
func UserCacheDir() (string, error)
UserCacheDir 返回用于用户特定缓存数据的默认根目录。 用户应该在这个目录下创建自己的应用程序特定的子目录, 并使用那个子目录。
在 Unix 系统上,如果 $XDG_CACHE_HOME 非空,则返回它, 其含义由 https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html 指定, 否则返回 $HOME/.cache。 在 Darwin 上,它返回 $HOME/Library/Caches。 在 Windows 上,它返回 %LocalAppData%。 在 Plan 9 上,它返回 $home/lib/cache。
如果无法确定位置(例如未定义 $HOME),或
$XDG_CACHE_HOME 中的路径是相对路径,则会返回错误。
Example
package main
import (
"log"
"os"
"path/filepath"
"sync"
)
func main() {
dir, dirErr := os.UserCacheDir()
if dirErr == nil {
dir = filepath.Join(dir, "ExampleUserCacheDir")
}
getCache := func(name string) ([]byte, error) {
if dirErr != nil {
return nil, &os.PathError{Op: "getCache", Path: name, Err: os.ErrNotExist}
}
return os.ReadFile(filepath.Join(dir, name))
}
var mkdirOnce sync.Once
putCache := func(name string, b []byte) error {
if dirErr != nil {
return &os.PathError{Op: "putCache", Path: name, Err: dirErr}
}
mkdirOnce.Do(func() {
if err := os.MkdirAll(dir, 0700); err != nil {
log.Printf("can't create user cache dir: %v", err)
}
})
return os.WriteFile(filepath.Join(dir, name), b, 0600)
}
// Read and store cached data.
// …
_ = getCache
_ = putCache
}
func UserConfigDir
func UserConfigDir() (string, error)
UserConfigDir 返回用于用户特定配置数据的默认根目录。 用户应该在这个目录下创建自己的应用程序特定的 子目录,并使用那个子目录。
在 Unix 系统上,如果 $XDG_CONFIG_HOME 非空,则返回它, 其含义由 https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html 指定, 否则返回 $HOME/.config。 在 Darwin 上,它返回 $HOME/Library/Application Support。 在 Windows 上,它返回 %AppData%。 在 Plan 9 上,它返回 $home/lib。
如果无法确定位置(例如未定义 $HOME),或
$XDG_CONFIG_HOME 中的路径是相对路径,则会返回错误。
Example
package main
import (
"bytes"
"log"
"os"
"path/filepath"
)
func main() {
dir, dirErr := os.UserConfigDir()
var (
configPath string
origConfig []byte
)
if dirErr == nil {
configPath = filepath.Join(dir, "ExampleUserConfigDir", "example.conf")
var err error
origConfig, err = os.ReadFile(configPath)
if err != nil && !os.IsNotExist(err) {
// The user has a config file but we couldn't read it.
// Report the error instead of ignoring their configuration.
log.Fatal(err)
}
}
// Use and perhaps make changes to the config.
config := bytes.Clone(origConfig)
// …
// Save changes.
if !bytes.Equal(config, origConfig) {
if configPath == "" {
log.Printf("not saving config changes: %v", dirErr)
} else {
err := os.MkdirAll(filepath.Dir(configPath), 0700)
if err == nil {
err = os.WriteFile(configPath, config, 0600)
}
if err != nil {
log.Printf("error saving config changes: %v", err)
}
}
}
}
func UserHomeDir
func UserHomeDir() (string, error)
UserHomeDir 返回当前用户的主目录。
在 Unix(包括 macOS)上,它返回 $HOME 环境变量。 在 Windows 上,它返回 %USERPROFILE%。 在 Plan 9 上,它返回 $home 环境变量。
如果环境中未设置期望的变量,UserHomeDir 会返回特定于平台的默认值或非 nil 的错误。
func WriteFile
func WriteFile(name string, data []byte, perm FileMode) error
WriteFile 将数据写入指定文件,必要时创建它。
如果文件不存在,WriteFile 会以权限 perm(在 umask 之前)创建它;
否则 WriteFile 在写入前先截断它,而不改变权限。
由于 WriteFile 需要多次系统调用才能完成,操作中途失败
可能会使文件处于部分写入的状态。
Example
package main
import (
"log"
"os"
)
func main() {
err := os.WriteFile("testdata/hello", []byte("Hello, Gophers!"), 0666)
if err != nil {
log.Fatal(err)
}
}
Types
type DirEntry
type DirEntry = fs.DirEntry
DirEntry 是从目录中读取的一个条目 (使用 ReadDir 函数或 File.ReadDir 方法)。
func ReadDir
func ReadDir(name string) ([]DirEntry, error)
ReadDir 读取指定名称的目录,
按文件名排序返回其所有目录条目。
如果读取目录时发生错误,
ReadDir 返回在出错之前能够读取的条目,
以及该错误。
Example
package main
import (
"fmt"
"log"
"os"
)
func main() {
files, err := os.ReadDir(".")
if err != nil {
log.Fatal(err)
}
for _, file := range files {
fmt.Println(file.Name())
}
}
type File
type File struct { // contains filtered or unexported fields }
File 表示一个打开的文件描述符。
File 的方法可安全地并发使用。
func Create
func Create(name string) (*File, error)
Create 创建或截断指定的文件。如果文件已存在, 则将其截断。如果文件不存在,则以模式 0o666 (在 umask 之前)创建。如果成功,可以使用返回的 File 上的 方法进行 I/O;关联的文件描述符具有模式 O_RDWR。 包含该文件的目录必须已经存在。 如果出错,错误的类型为 *PathError。
func CreateTemp
func CreateTemp(dir, pattern string) (*File, error)
CreateTemp 在目录 dir 中创建一个新的临时文件,
以读写方式打开该文件,并返回结果文件。
文件名通过在 pattern 末尾追加一个随机字符串生成。
如果 pattern 中包含 "*",随机字符串会替换最后一个 "*"。
文件以模式 0o600(受 umask 影响之前)创建。
如果 dir 为空字符串,CreateTemp 使用 TempDir 返回的默认临时文件目录。
多个程序或 goroutine 同时调用 CreateTemp 时不会选择同一个文件。
调用者可以使用文件的 Name 方法查找该文件的路径名。
当不再需要该文件时,删除它是调用者的责任。
Example
package main
import (
"log"
"os"
)
func main() {
f, err := os.CreateTemp("", "example")
if err != nil {
log.Fatal(err)
}
defer os.Remove(f.Name()) // clean up
if _, err := f.Write([]byte("content")); err != nil {
log.Fatal(err)
}
if err := f.Close(); err != nil {
log.Fatal(err)
}
}
Example (Suffix)
package main
import (
"log"
"os"
)
func main() {
f, err := os.CreateTemp("", "example.*.txt")
if err != nil {
log.Fatal(err)
}
defer os.Remove(f.Name()) // clean up
if _, err := f.Write([]byte("content")); err != nil {
f.Close()
log.Fatal(err)
}
if err := f.Close(); err != nil {
log.Fatal(err)
}
}
func NewFile
func NewFile(fd uintptr, name string) *File
NewFile 使用给定的文件描述符和名称返回一个新的 File。 如果 fd 不是有效的文件描述符,返回的值将为 nil。
NewFile 的行为在某些平台上有所不同:
- 在 Unix 上,如果 fd 处于非阻塞模式,NewFile 会尝试返回一个可轮询的文件。
- 在 Windows 上,如果 fd 是为异步 I/O 打开的(即在 syscall.CreateFile 调用中 指定了 syscall.FILE_FLAG_OVERLAPPED),NewFile 会通过将 fd 与 Go 运行时的 I/O 完成端口关联,尝试返回一个可轮询的文件。 如果关联失败,I/O 操作将以同步方式执行。
只有可轮询的文件才支持 File.SetDeadline、File.SetReadDeadline 和 File.SetWriteDeadline。
在将其传给 NewFile 之后,fd 可能会在 File.Fd 的注释中所描述的相同条件下变为无效, 并且适用相同的约束。
func Open
func Open(name string) (*File, error)
Open 打开指定的文件以供读取。如果成功,可以使用返回的文件上的 方法进行读取;关联的文件描述符具有模式 O_RDONLY。 如果出错,错误的类型为 *PathError。
func OpenFile
func OpenFile(name string, flag int, perm FileMode) (*File, error)
OpenFile 是通用的 open 调用;大多数用户会改用 Open
或 Create。它使用指定的标志(O_RDONLY 等)打开指定的文件。
如果文件不存在,并且传入了 O_CREATE 标志,
则以模式 perm(在 umask 之前)创建它;
包含它的目录必须存在。如果成功,
可以使用返回的 File 上的方法进行 I/O。
如果出错,错误的类型为 *PathError。
Example
package main
import (
"log"
"os"
)
func main() {
f, err := os.OpenFile("notes.txt", os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
log.Fatal(err)
}
if err := f.Close(); err != nil {
log.Fatal(err)
}
}
Example (Append)
package main
import (
"log"
"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 {
log.Fatal(err)
}
if _, err := f.Write([]byte("appended some data\n")); err != nil {
f.Close() // ignore error; Write error takes precedence
log.Fatal(err)
}
if err := f.Close(); err != nil {
log.Fatal(err)
}
}
func OpenInRoot
func OpenInRoot(dir, name string) (*File, error)
OpenInRoot 在目录 dir 中打开文件 name。 它等价于先执行 OpenRoot(dir),然后在根中打开该文件。
如果 name 的任何一个组件引用了 dir 之外的位置, OpenInRoot 会返回错误。
详情和限制参见 Root。
func (*File) Chdir
func (f *File) Chdir() error
Chdir 将当前工作目录更改为该文件, 该文件必须是目录。 如果出错,错误的类型为 *PathError。
func (*File) Chmod
func (f *File) Chmod(mode FileMode) error
Chmod 将文件的模式更改为 mode。 如果出错,错误的类型为 *PathError。
func (*File) Chown
func (f *File) Chown(uid, gid int) error
Chown 更改指定文件的数字 uid 和 gid。 如果出错,错误的类型为 *PathError。
在 Windows 上,它总是返回 syscall.EWINDOWS 错误, 并包装在 *PathError 中。
func (*File) Close
func (f *File) Close() error
Close 关闭 File,使其无法再用于 I/O。 在支持 File.SetDeadline 的文件上,任何挂起的 I/O 操作 都将被取消,并立即返回 ErrClosed 错误。 如果已经调用过 Close,Close 会返回错误。
func (*File) Fd
func (f *File) Fd() uintptr
Fd 返回引用已打开文件的系统文件描述符或句柄。 如果 f 已关闭,则该描述符变为无效。 如果 f 被垃圾回收,终结器可能会关闭该描述符, 使其无效;有关终结器何时可能运行的更多信息, 请参见 runtime.SetFinalizer。
不要关闭返回的描述符;这可能导致之后 关闭 f 时关闭了一个不相关的描述符。
Fd 的行为在某些平台上有所不同:
- 在 Unix 和 Windows 上,File.SetDeadline 方法将停止工作。
- 在 Windows 上,如果文件上没有并发的 I/O 操作,文件描述符将与 Go 运行时的 I/O 完成端口解除关联。
在大多数用途中,更推荐使用 f.SyscallConn 方法。
func (*File) Name
func (f *File) Name() string
Name 返回文件呈现给 Open 时的名称。
在 [Close] 之后调用 Name 是安全的。
func (*File) Read
func (f *File) Read(b []byte) (n int, err error)
Read 从 File 中读取最多 len(b) 个字节并存储到 b 中。 它返回读取的字节数以及遇到的任何错误。 在文件末尾,Read 返回 0、io.EOF。
func (*File) ReadAt
func (f *File) ReadAt(b []byte, off int64) (n int, err error)
ReadAt 从 File 中从字节偏移量 off 开始读取 len(b) 个字节。 它返回读取的字节数和错误(如果有)。 当 n < len(b) 时,ReadAt 总是返回非 nil 的错误。 在文件末尾,该错误为 io.EOF。
func (*File) ReadDir
func (f *File) ReadDir(n int) ([]DirEntry, error)
ReadDir 读取与文件 f 关联的目录的内容, 并按目录顺序返回一个 DirEntry 值的切片。 对同一文件的后续调用将产生目录中更靠后的 DirEntry 记录。
如果 n > 0,ReadDir 最多返回 n 个 DirEntry 记录。 在这种情况下,如果 ReadDir 返回空切片,它将返回一个解释原因的错误。 在目录末尾,该错误为 io.EOF。
如果 n <= 0,ReadDir 返回目录中剩余的所有 DirEntry 记录。 成功时,它返回 nil 错误(而非 io.EOF)。
func (*File) ReadFrom
func (f *File) ReadFrom(r io.Reader) (n int64, err error)
ReadFrom 实现 io.ReaderFrom。
func (*File) Readdir
func (f *File) Readdir(n int) ([]FileInfo, error)
Readdir 读取与 file 关联的目录的内容, 并按目录顺序返回至多 n 个 FileInfo 值的切片, 其内容与 Lstat 返回的相同。对同一文件的后续调用将 产生更多的 FileInfo。
如果 n > 0,Readdir 最多返回 n 个 FileInfo 结构。在这种情况下, 如果 Readdir 返回空切片,它将返回一个解释原因的非 nil 错误。 在目录末尾,该错误为 io.EOF。
如果 n <= 0,Readdir 在单个切片中返回目录中的所有 FileInfo。 在这种情况下,如果 Readdir 成功(一直读取到目录末尾), 它将返回该切片和 nil 错误。如果在到达目录末尾之前 遇到错误,Readdir 返回截至该处读取的 FileInfo 和一个非 nil 错误。
大多数客户端更适合使用更高效的 ReadDir 方法。
func (*File) Readdirnames
func (f *File) Readdirnames(n int) (names []string, err error)
Readdirnames 读取与 file 关联的目录的内容, 并按目录顺序返回至多 n 个目录中文件名的切片。 对同一文件的后续调用将产生更多的文件名。
如果 n > 0,Readdirnames 最多返回 n 个名称。在这种情况下, 如果 Readdirnames 返回空切片,它将返回一个解释原因的非 nil 错误。 在目录末尾,该错误为 io.EOF。
如果 n <= 0,Readdirnames 在单个切片中返回目录中的所有名称。 在这种情况下,如果 Readdirnames 成功(一直读取到目录末尾), 它将返回该切片和 nil 错误。如果在到达目录末尾之前 遇到错误,Readdirnames 返回截至该处读取的名称和一个非 nil 错误。
func (*File) Seek
func (f *File) Seek(offset int64, whence int) (ret int64, err error)
Seek 将文件上下一次 Read 或 Write 的偏移量设置为 offset, 其解释取决于 whence:0 表示相对于文件起始位置,1 表示 相对于当前偏移量,2 表示相对于末尾。 它返回新的偏移量和错误(如果有)。 对以 O_APPEND 打开的文件,Seek 的行为未指定。
func (*File) SetDeadline
func (f *File) SetDeadline(t time.Time) error
SetDeadline 为 File 设置读取和写入截止时间。 它等价于同时调用 SetReadDeadline 和 SetWriteDeadline。
只有某些类型的文件支持设置截止时间。对不支持截止时间的文件 调用 SetDeadline 将返回 ErrNoDeadline。 在大多数系统上,普通文件不支持截止时间,但管道支持。
截止时间是一个绝对时间,超过它之后 I/O 操作会失败并返回 错误,而不是阻塞。截止时间适用于所有未来的和挂起的 I/O,而不仅仅是紧随其后的 Read 或 Write 调用。 在超过截止时间之后,可以通过将截止时间设置到未来 来刷新连接。
如果超过截止时间,对 Read 或 Write 或其他 I/O 方法的调用会返回一个包装了 ErrDeadlineExceeded 的错误。 这可以使用 errors.Is(err, os.ErrDeadlineExceeded) 来检测。 该错误实现了 Timeout 方法,调用 Timeout 方法会返回 true,但还有其他一些错误 即使未超过截止时间,Timeout 也会返回 true。
可以通过在成功的 Read 或 Write 调用之后反复延长 截止时间来实现空闲超时。
t 的零值表示 I/O 操作不会超时。
func (*File) SetReadDeadline
func (f *File) SetReadDeadline(t time.Time) error
SetReadDeadline 为未来的 Read 调用以及任何 当前阻塞的 Read 调用设置截止时间。 t 的零值表示 Read 不会超时。 并非所有文件都支持设置截止时间;参见 SetDeadline。
func (*File) SetWriteDeadline
func (f *File) SetWriteDeadline(t time.Time) error
SetWriteDeadline 为任何未来的 Write 调用以及任何 当前阻塞的 Write 调用设置截止时间。 即使 Write 超时,它也可能返回 n > 0,表示 部分数据已成功写入。 t 的零值表示 Write 不会超时。 并非所有文件都支持设置截止时间;参见 SetDeadline。
func (*File) Stat
func (f *File) Stat() (FileInfo, error)
Stat 返回描述文件的 FileInfo 结构。 如果出错,错误的类型为 *PathError。
func (*File) Sync
func (f *File) Sync() error
Sync 将文件的当前内容提交到稳定存储。 通常,这意味着将文件系统对最近写入数据的内存副本 刷新到磁盘。
func (*File) SyscallConn
func (f *File) SyscallConn() (syscall.RawConn, error)
SyscallConn 返回一个原始文件。 这实现了 syscall.Conn 接口。
func (*File) Truncate
func (f *File) Truncate(size int64) error
Truncate 更改文件的大小。 它不会改变 I/O 偏移量。 如果出错,错误的类型为 *PathError。
func (*File) Write
func (f *File) Write(b []byte) (n int, err error)
Write 从 b 向 File 写入 len(b) 个字节。 它返回写入的字节数和错误(如果有)。 当 n != len(b) 时,Write 返回非 nil 的错误。
func (*File) WriteAt
func (f *File) WriteAt(b []byte, off int64) (n int, err error)
WriteAt 从字节偏移量 off 开始向 File 写入 len(b) 个字节。 它返回写入的字节数和错误(如果有)。 当 n != len(b) 时,WriteAt 返回非 nil 的错误。
如果文件是以 O_APPEND 标志打开的,WriteAt 会返回错误。
func (*File) WriteString
func (f *File) WriteString(s string) (n int, err error)
WriteString 类似于 Write,但写入的是字符串 s 的内容, 而不是字节切片。
func (*File) WriteTo
func (f *File) WriteTo(w io.Writer) (n int64, err error)
WriteTo 实现 io.WriterTo。
type FileInfo
type FileInfo = fs.FileInfo
FileInfo 描述一个文件,由 Stat 和 Lstat 返回。
func Lstat
func Lstat(name string) (FileInfo, error)
Lstat 返回描述指定文件的 FileInfo。 如果该文件是符号链接,返回的 FileInfo 描述的是该符号链接。Lstat 不会尝试跟随该链接。 如果出错,错误的类型为 *PathError。
在 Windows 上,如果该文件是一个作为另一个命名实体(例如符号链接或 挂载文件夹)替代的重解析点,返回的 FileInfo 描述该重解析点, 并且不会尝试解析它。
func Stat
func Stat(name string) (FileInfo, error)
Stat 返回描述指定文件的 FileInfo。 如果出错,错误的类型为 *PathError。
type FileMode
type FileMode = fs.FileMode
FileMode 表示一个文件的模式和权限位。
这些位在所有系统上具有相同的定义,因此
关于文件的信息可以可移植地从一个系统
移动到另一个系统。并非所有位都适用于所有系统。
对于目录,唯一必需的位是 ModeDir。
Example
package main
import (
"fmt"
"io/fs"
"log"
"os"
)
func main() {
fi, err := os.Lstat("some-filename")
if err != nil {
log.Fatal(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&fs.ModeSymlink != 0:
fmt.Println("symbolic link")
case mode&fs.ModeNamedPipe != 0:
fmt.Println("named pipe")
}
}
type LinkError
type LinkError struct { Op string Old string New string Err error }
LinkError 记录链接、符号链接或重命名系统调用期间的错误 以及导致该错误的路径。
func (*LinkError) Error
func (e *LinkError) Error() string
func (*LinkError) Unwrap
func (e *LinkError) Unwrap() error
type PathError
type PathError = fs.PathError
PathError 记录一个错误以及导致它的操作和文件路径。
type ProcAttr
type ProcAttr struct { // 如果 Dir 非空,子进程会在创建进程之前 // 切换到该目录。 Dir string // 如果 Env 非 nil,它以 Environ 返回的形式给出 // 新进程的环境变量。 // 如果为 nil,将使用 Environ 的结果。 Env []string // Files 指定新进程继承的已打开文件。前三个条目 // 分别对应标准输入、标准输出和标准错误。 // 根据底层操作系统的不同,实现可能支持额外的条目。 // nil 条目表示该文件在进程启动时被关闭。 // 在 Unix 系统上,StartProcess 会将这些 File 值 // 改为阻塞模式,这意味着 SetDeadline 将停止工作, // 并且调用 Close 不会中断 Read 或 Write。 Files []*File // 操作系统特定的进程创建属性。 // 注意,设置此字段意味着你的程序 // 在某些操作系统上可能无法正确执行, // 甚至无法编译。 Sys *syscall.SysProcAttr }
ProcAttr 保存将应用于由 StartProcess 启动的 新进程的属性。
type Process
type Process struct { Pid int // contains filtered or unexported fields }
Process 存储由 StartProcess 创建的进程的信息。
func FindProcess
func FindProcess(pid int) (*Process, error)
FindProcess 根据 pid 查找正在运行的进程。
它返回的 Process 可用于获取 底层操作系统进程的信息。
在 Unix 系统上,无论进程是否存在,FindProcess 总是成功 并为给定的 pid 返回一个 Process。要测试进程是否 实际存在,请查看 p.Signal(syscall.Signal(0)) 是否报告错误。
func StartProcess
func StartProcess(name string, argv []string, attr *ProcAttr) (*Process, error)
StartProcess 使用由 name、argv 和 attr 指定的程序、参数和属性 启动一个新进程。argv 切片将成为新进程中的 os.Args, 因此它通常以程序名开头。
如果调用 goroutine 已使用 runtime.LockOSThread 锁定了操作系统线程, 并修改了任何可继承的操作系统级线程状态 (例如 Linux 或 Plan 9 命名空间),则新进程 将继承调用者的线程状态。
StartProcess 是一个低级接口。os/exec 包提供了 更高级的接口。
如果发生错误,其类型将是 *PathError。
func (*Process) Kill
func (p *Process) Kill() error
Kill 使 Process 立即退出。Kill 不会等到 Process 实际退出。它只杀死 Process 本身, 而不杀死它可能启动的任何其他进程。
func (*Process) Release
func (p *Process) Release() error
Release 释放与 Process p 关联的任何资源, 使其在以后不可用。 仅在未调用 Process.Wait 时才需要调用 Release。
func (*Process) Signal
func (p *Process) Signal(sig Signal) error
Signal 向 Process 发送信号。 在 Windows 上发送 Interrupt 尚未实现。
func (*Process) Wait
func (p *Process) Wait() (*ProcessState, error)
Wait 等待 Process 退出,然后返回一个 描述其状态的 ProcessState 以及错误(如果有)。 Wait 释放与 Process 关联的任何资源。 在大多数操作系统上,Process 必须是当前进程的 子进程,否则将返回错误。
func (*Process) WithHandle
func (p *Process) WithHandle(f func(handle uintptr)) error
WithHandle 调用提供的函数 f,并将一个有效的进程句柄 作为参数。该句柄保证在 f 返回之前一直指向进程 p, 即使 p 已终止。此函数不能在 Process.Release 或 Process.Wait 之后使用。
如果不支持进程句柄或句柄不可用, 它返回 ErrNoHandle。目前,进程句柄在 Linux 5.4 或更高版本(pidfd)以及 Windows 上受支持。
type ProcessState
type ProcessState struct { // contains filtered or unexported fields }
ProcessState 存储由 Wait 报告的有关进程的信息。
func (*ProcessState) ExitCode
func (p *ProcessState) ExitCode() int
ExitCode 返回已退出进程的退出码,如果进程尚未退出或被信号终止,则返回 -1。
func (*ProcessState) Exited
func (p *ProcessState) Exited() bool
Exited 报告程序是否已退出。 在 Unix 系统上,如果程序因调用 exit 而退出,则报告 true, 如果程序因信号而终止,则报告 false。
func (*ProcessState) Pid
func (p *ProcessState) Pid() int
Pid 返回已退出进程的进程 id。
func (*ProcessState) String
func (p *ProcessState) String() string
func (*ProcessState) Success
func (p *ProcessState) Success() bool
Success 报告程序是否成功退出, 例如在 Unix 上以退出状态 0 退出。
func (*ProcessState) Sys
func (p *ProcessState) Sys() any
Sys 返回关于进程的依赖于系统的退出信息。 将其转换为合适的底层类型, 例如 Unix 上的 syscall.WaitStatus,以访问其内容。
func (*ProcessState) SysUsage
func (p *ProcessState) SysUsage() any
SysUsage 返回关于已退出进程的依赖于系统的资源使用信息。 将其转换为合适的底层类型, 例如 Unix 上的 *syscall.Rusage,以访问其内容。 (在 Unix 上,*syscall.Rusage 与 getrusage(2) 手册页中 定义的 struct rusage 匹配。)
func (*ProcessState) SystemTime
func (p *ProcessState) SystemTime() time.Duration
SystemTime 返回已退出进程及其子进程的系统 CPU 时间。
func (*ProcessState) UserTime
func (p *ProcessState) UserTime() time.Duration
UserTime 返回已退出进程及其子进程的用户 CPU 时间。
type Root
type Root struct { // contains filtered or unexported fields }
Root 可用于仅访问单个目录树内的文件。
Root 上的方法只能访问根目录之下的文件和目录。 如果传给 Root 方法的文件名的任何一个组件引用了 根之外的位置,该方法会返回错误。 文件名可以引用目录本身(.)。
Root 上的方法会跟随符号链接,但符号链接不得 引用根之外的位置。 符号链接不得是绝对路径。
Root 上的方法不禁止跨越文件系统边界、Linux 绑定挂载、 /proc 特殊文件,或访问 Unix 设备文件。
Root 上的方法可以安全地同时从多个 goroutine 使用。
在大多数平台上,创建 Root 会打开一个引用该目录的 文件描述符或句柄。如果该目录被移动,Root 上的方法 引用的是其新位置处的原目录。
Root 的行为在某些平台上有所不同:
- 当 GOOS=windows 时,文件名不得引用 Windows 保留的设备名, 例如 NUL 和 COM1。
- 在 Unix 上,Root.Chmod、Root.Chown 和 Root.Chtimes 容易受到竞态条件影响。 如果操作的目标在操作进行期间从普通文件变为符号链接, 该操作可能会作用于链接本身而非链接目标。
- 当 GOOS=js 时,Root 在符号链接验证中容易受到 TOCTOU (检查时-使用时)攻击,且无法保证操作不会逃逸出根。
- 当 GOOS=plan9 或 GOOS=js 时,Root 不会跨重命名跟踪目录。 在这些平台上,Root 引用的是目录名,而不是文件描述符。
- WASI preview 1(GOOS=wasip1)不支持 Root.Chmod。
func OpenRoot
func OpenRoot(name string) (*Root, error)
OpenRoot 打开指定的目录。 它会跟随目录名中的符号链接。 如果出错,错误的类型为 *PathError。
func (*Root) Chmod
func (r *Root) Chmod(name string, mode FileMode) error
Chmod 将根中指定文件的模式更改为 mode。 更多详情参见 Chmod。
func (*Root) Chown
func (r *Root) Chown(name string, uid, gid int) error
Chown 更改根中指定文件的数字 uid 和 gid。 更多详情参见 Chown。
func (*Root) Chtimes
func (r *Root) Chtimes(name string, atime time.Time, mtime time.Time) error
Chtimes 更改根中指定文件的访问时间和修改时间。 更多详情参见 Chtimes。
func (*Root) Close
func (r *Root) Close() error
Close 关闭该 Root。 调用 Close 之后,Root 上的方法会返回错误。
func (*Root) Create
func (r *Root) Create(name string) (*File, error)
Create 在根中创建或截断指定的文件。 更多详情参见 Create。
func (*Root) FS
func (r *Root) FS() fs.FS
FS 返回一个用于根中文件树的文件系统(一个 fs.FS)。
结果实现了 io/fs.StatFS、io/fs.ReadFileFS、 io/fs.ReadDirFS 和 io/fs.ReadLinkFS。
func (*Root) Lchown
func (r *Root) Lchown(name string, uid, gid int) error
Lchown 更改根中指定文件的数字 uid 和 gid。 更多详情参见 Lchown。
func (*Root) Link
func (r *Root) Link(oldname, newname string) error
Link 将 newname 创建为指向 oldname 文件的硬链接。 两个路径都相对于根。 更多详情参见 Link。
如果 oldname 是符号链接,Link 创建的是指向 oldname 而非其目标的新链接。 此行为在某些平台上可能与 Link 的行为不同。
当 GOOS=js 时,如果 oldname 是符号链接,Link 会返回错误。
func (*Root) Lstat
func (r *Root) Lstat(name string) (FileInfo, error)
Lstat 返回描述根中指定文件的 FileInfo。 如果该文件是符号链接,返回的 FileInfo 描述的是该符号链接。 更多详情参见 Lstat。
func (*Root) Mkdir
func (r *Root) Mkdir(name string, perm FileMode) error
Mkdir 在根中创建一个新目录, 使用指定的名称和权限位(在 umask 之前)。 更多详情参见 Mkdir。
如果 perm 包含除九个最低有效位(0o777)之外的位, Mkdir 会返回错误。
func (*Root) MkdirAll
func (r *Root) MkdirAll(name string, perm FileMode) error
MkdirAll 在根中创建一个新目录,以及任何必要的父目录。 更多详情参见 MkdirAll。
如果 perm 包含除九个最低有效位(0o777)之外的位, MkdirAll 会返回错误。
func (*Root) Name
func (r *Root) Name() string
Name 返回传给 OpenRoot 的目录名。
在 [Close] 之后调用 Name 是安全的。
func (*Root) Open
func (r *Root) Open(name string) (*File, error)
Open 以只读方式打开根中指定的文件。 更多详情参见 Open。
func (*Root) OpenFile
func (r *Root) OpenFile(name string, flag int, perm FileMode) (*File, error)
OpenFile 打开根中指定的文件。 更多详情参见 OpenFile。
如果 perm 包含除九个最低有效位(0o777)之外的位, OpenFile 会返回错误。
func (*Root) OpenRoot
func (r *Root) OpenRoot(name string) (*Root, error)
OpenRoot 打开根中指定的目录。 如果出错,错误的类型为 *PathError。
func (*Root) ReadFile
func (r *Root) ReadFile(name string) ([]byte, error)
ReadFile 读取根中指定的文件并返回其内容。 更多详情参见 ReadFile。
func (*Root) Readlink
func (r *Root) Readlink(name string) (string, error)
Readlink 返回根中指定符号链接的目标。 更多详情参见 Readlink。
func (*Root) Remove
func (r *Root) Remove(name string) error
Remove 删除根中指定的文件或(空)目录。 更多详情参见 Remove。
func (*Root) RemoveAll
func (r *Root) RemoveAll(name string) error
RemoveAll 删除根中指定的文件或目录及其包含的所有子项。 更多详情参见 RemoveAll。
func (*Root) Rename
func (r *Root) Rename(oldname, newname string) error
Rename 将 oldname 重命名(移动)为 newname。 两个路径都相对于根。 更多详情参见 Rename。
func (*Root) Stat
func (r *Root) Stat(name string) (FileInfo, error)
Stat 返回描述根中指定文件的 FileInfo。 更多详情参见 Stat。
func (*Root) Symlink
func (r *Root) Symlink(oldname, newname string) error
Symlink 将 newname 创建为指向 oldname 的符号链接。 更多详情参见 Symlink。
Symlink 不校验 oldname, 它可能引用根之外的位置。
在 Windows 上,如果 oldname 引用了根内的目录, 则创建目录链接。否则创建文件链接。
func (*Root) WriteFile
func (r *Root) WriteFile(name string, data []byte, perm FileMode) error
WriteFile 将 data 写入根中指定的文件,必要时创建它。 更多详情参见 WriteFile。
type Signal
type Signal interface { String() string Signal() // 用于与其他 Stringer 区分 }
Signal 表示操作系统信号。 通常的底层实现依赖于操作系统: 在 Unix 上它是 syscall.Signal。
var ( Interrupt Signal = syscall.SIGINT Kill Signal = syscall.SIGKILL )
在所有系统上,os 包中保证存在的唯一信号值是 os.Interrupt(向进程发送中断) 和 os.Kill(强制进程退出)。在 Windows 上,使用 os.Process.Signal 向进程发送 os.Interrupt 未实现;它会返回错误而不是发送信号。
type SyscallError
type SyscallError struct { Syscall string Err error }
SyscallError 记录来自特定系统调用的错误。
func (*SyscallError) Error
func (e *SyscallError) Error() string
func (*SyscallError) Timeout
func (e *SyscallError) Timeout() bool
Timeout 报告此错误是否表示超时。
func (*SyscallError) Unwrap
func (e *SyscallError) Unwrap() error
Directories
| exec | Package exec 运行外部命令。 |
| signal | Package signal 实现对传入信号的访问。 |
| user | Package user 允许按名称或 id 查找用户账户。 |