目录 搜索
archive archive/tar archive/zip bufio bufio(缓存) builtin builtin(内置包) bytes bytes(包字节) compress compress/bzip2(压缩/bzip2) compress/flate(压缩/flate) compress/gzip(压缩/gzip) compress/lzw(压缩/lzw) compress/zlib(压缩/zlib) container container/heap(容器数据结构heap) container/list(容器数据结构list) container/ring(容器数据结构ring) context context(上下文) crypto crypto(加密) crypto/aes(加密/aes) crypto/cipher(加密/cipher) crypto/des(加密/des) crypto/dsa(加密/dsa) crypto/ecdsa(加密/ecdsa) crypto/elliptic(加密/elliptic) crypto/hmac(加密/hmac) crypto/md5(加密/md5) crypto/rand(加密/rand) crypto/rc4(加密/rc4) crypto/rsa(加密/rsa) crypto/sha1(加密/sha1) crypto/sha256(加密/sha256) crypto/sha512(加密/sha512) crypto/subtle(加密/subtle) crypto/tls(加密/tls) crypto/x509(加密/x509) crypto/x509/pkix(加密/x509/pkix) database database/sql(数据库/sql) database/sql/driver(数据库/sql/driver) debug debug/dwarf(调试/dwarf) debug/elf(调试/elf) debug/gosym(调试/gosym) debug/macho(调试/macho) debug/pe(调试/pe) debug/plan9obj(调试/plan9obj) encoding encoding(编码) encoding/ascii85(编码/ascii85) encoding/asn1(编码/asn1) encoding/base32(编码/base32) encoding/base64(编码/base64) encoding/binary(编码/binary) encoding/csv(编码/csv) encoding/gob(编码/gob) encoding/hex(编码/hex) encoding/json(编码/json) encoding/pem(编码/pem) encoding/xml(编码/xml) errors errors(错误) expvar expvar flag flag(命令行参数解析flag包) fmt fmt go go/ast(抽象语法树) go/build go/constant(常量) go/doc(文档) go/format(格式) go/importer go/parser go/printer go/scanner(扫描仪) go/token(令牌) go/types(类型) hash hash(散列) hash/adler32 hash/crc32 hash/crc64 hash/fnv html html html/template(模板) image image(图像) image/color(颜色) image/color/palette(调色板) image/draw(绘图) image/gif image/jpeg image/png index index/suffixarray io io io/ioutil log log log/syslog(日志系统) math math math/big math/big math/bits math/bits math/cmplx math/cmplx math/rand math/rand mime mime mime/multipart(多部分) mime/quotedprintable net net net/http net/http net/http/cgi net/http/cookiejar net/http/fcgi net/http/httptest net/http/httptrace net/http/httputil net/http/internal net/http/pprof net/mail net/mail net/rpc net/rpc net/rpc/jsonrpc net/smtp net/smtp net/textproto net/textproto net/url net/url os os os/exec os/signal os/user path path path/filepath(文件路径) plugin plugin(插件) reflect reflect(反射) regexp regexp(正则表达式) regexp/syntax runtime runtime(运行时) runtime/debug(调试) runtime/internal/sys runtime/pprof runtime/race(竞争) runtime/trace(执行追踪器) sort sort(排序算法) strconv strconv(转换) strings strings(字符串) sync sync(同步) sync/atomic(原子操作) syscall syscall(系统调用) testing testing(测试) testing/iotest testing/quick text text/scanner(扫描文本) text/tabwriter text/template(定义模板) text/template/parse time time(时间戳) unicode unicode unicode/utf16 unicode/utf8 unsafe unsafe
文字

  • import "os"

  • Overview

  • Index

  • Examples

  • Subdirectories

概观

Package os为操作系统功能提供了一个平台无关的接口。虽然错误处理类似于 Go,但设计类似 Unix,失败的调用返回类型错误的值而不是错误号。错误中通常会提供更多信息。例如,如果接收文件名的调用失败(例如 Open 或 Stat ),则错误将在打印时包含失败的文件名,并且将是 * PathError 类型,可能会解压缩以获取更多信息。

OS 界面旨在使所有操作系统均匀。通常不可用的功能出现在系统特定的软件包 syscall 中。

这里有一个简单的例子,打开一个文件并阅读一些文件。

file, err := os.Open("file.go") // For read access.if err != nil {
	log.Fatal(err)}

如果打开失败,错误字符串将不言自明,如

open file.go: no such file or directory

然后可以将文件的数据读入一段字节。读取和写入从参数切片的长度获取其字节数。

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

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 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 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 NewSyscallError(syscall string, err error) 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

  • type File

  • func Create(name 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 Pipe() (r *File, w *File, err 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) ([]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) Stat() (FileInfo, error)

  • func (f *File) Sync() 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)

  • type FileInfo

  • func Lstat(name string) (FileInfo, error)

  • func Stat(name string) (FileInfo, error)

  • type FileMode

  • func (m FileMode) IsDir() bool

  • func (m FileMode) IsRegular() bool

  • func (m FileMode) Perm() FileMode

  • func (m FileMode) String() string

  • type LinkError

  • func (e *LinkError) Error() string

  • type PathError

  • func (e *PathError) Error() string

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

  • type ProcessState

  • func (p *ProcessState) Exited() bool

  • func (p *ProcessState) Pid() int

  • func (p *ProcessState) String() string

  • func (p *ProcessState) Success() bool

  • func (p *ProcessState) Sys() interface{}

  • func (p *ProcessState) SysUsage() interface{}

  • func (p *ProcessState) SystemTime() time.Duration

  • func (p *ProcessState) UserTime() time.Duration

  • type Signal

  • type SyscallError

  • func (e *SyscallError) Error() string

例子

Chmod Chtimes ExpandEnv FileMode Getenv IsNotExist LookupEnv OpenFile OpenFile (Append) Unsetenv

包文件

dir.go dir_unix.go env.go error.go error_posix.go error_unix.go exec.go exec_posix.go exec_unix.go executable.go executable_procfs.go file.go file_posix.go file_unix.go getwd.go path.go path_unix.go pipe_linux.go proc.go stat_linux.go stat_unix.go sticky_notbsd.go str.go sys.go sys_linux.go sys_unix.go types.go types_unix.go wait_waitid.go

常量

标记为 OpenFile 封装底层系统的标记。并非所有的标志都可以在给定的系统上实现。

const (
        O_RDONLY int = syscall.O_RDONLY // open the file read-only.
        O_WRONLY int = syscall.O_WRONLY // open the file write-only.
        O_RDWR   int = syscall.O_RDWR   // open the file read-write.
        O_APPEND int = syscall.O_APPEND // append data to the file when writing.
        O_CREATE int = syscall.O_CREAT  // create a new file if none exists.
        O_EXCL   int = syscall.O_EXCL   // used with O_CREATE, file must not exist
        O_SYNC   int = syscall.O_SYNC   // open for synchronous I/O.
        O_TRUNC  int = syscall.O_TRUNC  // if possible, truncate file when opened.)

寻求哪些价值。

Deprecated: Use io.SeekStart, io.SeekCurrent, and io.SeekEnd.

const (
        SEEK_SET int = 0 // seek relative to the origin of the file
        SEEK_CUR int = 1 // seek relative to the current offset
        SEEK_END int = 2 // seek relative to the end)
const (
        PathSeparator     = '/' // OS-specific path separator
        PathListSeparator = ':' // OS-specific path list separator)

DevNull 是操作系统“空设备”的名称。在类 Unix 系统上,它是“/ dev / null”; 在Windows上,“NUL”。

const DevNull = "/dev/null"

变量

一些常见系统调用错误的便携式模拟器。

var (
        ErrInvalid    = errors.New("invalid argument") // methods on File will return this error when the receiver is nil
        ErrPermission = errors.New("permission denied")
        ErrExist      = errors.New("file already exists")
        ErrNotExist   = errors.New("file does not exist")
        ErrClosed     = errors.New("file already closed"))

Stdin,Stdout 和 Stderr 是打开的文件,指向标准输入,标准输出和标准错误文件描述符。

请注意,Go 运行时写入标准错误以防恐慌和崩溃;关闭 Stderr 可能会导致这些消息到其他地方,也许会导致稍后打开的文件。

var (
        Stdin  = NewFile(uintptr(syscall.Stdin), "/dev/stdin")
        Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout")
        Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr"))

参数从程序名称开始保存命令行参数。

var Args []string

func Chdir

func Chdir(dir string) error

Chdir 将当前工作目录更改为指定的目录。如果有错误,它将是 * PathError 类型。

func Chmod

func Chmod(name string, mode FileMode) error

Chmod 将指定文件的模式更改为模式。如果文件是符号链接,它将更改链接目标的模式。如果有错误,它将是 * PathError 类型。

取决于操作系统,使用模式位的不同子集。

在 Unix 上,使用模式的权限位 ModeSetuid,ModeSetgid 和 ModeSticky 。

在 Windows 上,模式必须是非零的,否则只能使用0200位(所有者可写)模式; 它控制文件的只读属性是设置还是清除。属性。其他位当前未使用。对于只读文件使用模式0400,对于可读+可写文件使用0600。

在计划9中,使用模式的许可位 ModeAppend,ModeExclusive 和 ModeTemporary 。

package mainimport ("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 。如果有错误,它将是 * PathError 类型。

在 Windows 上,它总是返回包装在 * PathError 中的 syscall.EWINDOWS 错误。

func Chtimes

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

Chtimes 更改指定文件的访问和修改时间,类似于 Unix utime() 或 utimes() 函数。

底层文件系统可能会将值截断或舍入到不太精确的时间单位。如果有错误,它将是 * PathError 类型。

package mainimport ("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 Environ

func Environ() []string

Environ 以 “key = value” 的形式返回表示环境的字符串的副本。

func Executable

func Executable() (string, error)

可执行文件返回启动当前进程的可执行文件的路径名称。不能保证路径仍然指向正确的可执行文件。如果使用符号链接来启动进程,则根据操作系统的不同,结果可能是符号链接或它指向的路径。如果需要稳定的结果, path / filepath.EvalSymlinks 可能会有所帮助。

除非发生错误,否则可执行文件将返回绝对路径。

主要用例是找到相对于可执行文件的资源。

nacl 不支持可执行文件。

func Exit

func Exit(code int)

退出时会导致当前程序退出并显示给定的状态码。通常,代码0表示成功,错误不为零。该程序立即终止; 延迟功能不运行。

func Expand

func Expand(s string, mapping func(string) string) string

根据映射函数展开取代字符串中的 $ {var} 或 $ var 。例如,os.ExpandEnv(s) 等同于 os.Expand(s,os.Getenv)。

func ExpandEnv

func ExpandEnv(s string) string

ExpandEnv 根据当前环境变量的值替换字符串中的 $ {var} 或 $ var。未定义变量的引用被空字符串替换。

package mainimport ("fmt""os")func main() {
	fmt.Println(os.ExpandEnv("$USER lives in ${HOME}."))}

func Getegid

func Getegid() int

Getegid 返回调用者的数字有效组 ID 。

在 Windows 上,它返回-1。

func Getenv

func Getenv(key string) string

Getenv 检索由密钥命名的环境变量的值。它返回值,如果该变量不存在,该值将为空。要区分空值和未设值,请使用 LookupEnv 。

package mainimport ("fmt""os")func main() {
	fmt.Printf("%s lives in %s.\n", os.Getenv("USER"), os.Getenv("HOME"))}

func Geteuid

func Geteuid() int

Geteuid 返回调用者的数字有效用户标识。

在 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 返回调用者的数字用户标识。

在 Windows 上,它返回-1。

func Getwd

func Getwd() (dir string, err error)

Getwd 返回与当前目录对应的根路径名称。如果当前目录可以通过多个路径到达(由于符号链接),Getwd 可以返回其中任何一个。

func Hostname

func Hostname() (name string, err error)

主机名返回内核报告的主机名。

func IsExist

func IsExist(err error) bool

IsExist 返回一个布尔值,指示是否已知错误报告文件或目录已存在。它由 ErrExist 满足以及一些系统调用错误。

func IsNotExist

func IsNotExist(err error) bool

IsNotExist 返回一个布尔值,指示是否已知错误报告文件或目录不存在。它由 ErrNotExist 以及一些系统调用错误满足。

package mainimport ("fmt""os")func main() {
	filename := "a-nonexistent-file"if _, err := os.Stat(filename); os.IsNotExist(err) {
		fmt.Printf("file does not exist")}}

func IsPathSeparator

func IsPathSeparator(c uint8) bool

IsPathSeparator 报告 c 是否是目录分隔符。

func IsPermission

func IsPermission(err error) bool

IsPermission 返回一个布尔值,指示是否已知错误报告许可被拒绝。它由 ErrPermission 以及一些系统调用错误满足。

func Lchown

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

Lchown 更改指定文件的数字 uid 和 gid 。如果该文件是符号链接,它会更改链接本身的 uid 和 gid 。如果有错误,它将是 * PathError 类型。

在 Windows 上,它总是返回包装在 * PathError 中的 syscall.EWINDOWS 错误。

func Link

func Link(oldname, newname string) error

链接创建新名称作为旧名称文件的硬链接。如果有错误,它将是 * LinkError 类型。

func LookupEnv

func LookupEnv(key string) (string, bool)

LookupEnv 检索由密钥命名的环境变量的值。如果变量存在于环境中,则返回值(可能为空),布尔值为 true 。否则,返回的值将为空,布尔值将为 false 。

package mainimport ("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)}}show("USER")show("GOPATH")}

func Mkdir

func Mkdir(name string, perm FileMode) error

Mkdir 使用指定的名称和权限位创建一个新目录。如果有错误,它将是 * PathError 类型。

func MkdirAll

func MkdirAll(path string, perm FileMode) error

MkdirAll 会创建一个名为 path 的目录以及任何必要的父项,并返回 nil ,否则返回错误。许可位 perm 用于 MkdirAll 创建的所有目录。如果 path 已经是一个目录,MkdirAll 什么也不做,并返回 nil 。

func NewSyscallError

func NewSyscallError(syscall string, err error) error

NewSyscallError 返回一个新的 SyscallError 作为错误,并给出系统调用名称和错误详细信息。为方便起见,如果 err 为零,则 NewSyscallError 返回 nil 。

func Readlink

func Readlink(name string) (string, error)

Readlink 返回指定符号链接的目的地。如果有错误,它将是 * PathError 类型。

func Remove

func Remove(name string) error

删除将删除指定的文件或目录。如果有错误,它将是 * PathError 类型。

func RemoveAll

func RemoveAll(path string) error

RemoveAll 移除路径及其包含的任何子项。它删除所有可能的东西,但返回遇到的第一个错误。如果路径不存在,RemoveAll 返回 nil(无错误)。

func Rename

func Rename(oldpath, newpath string) error

重命名(移动)旧路径到新路径。如果 newpath 已经存在并且不是目录,则重命名将替换它。当 oldpath和 newpath 位于不同的目录中时,可能会应用 OS 特定的限制。如果有错误,它将是 * LinkError 类型。

func SameFile

func SameFile(fi1, fi2 FileInfo) bool

SameFile 报告 fi1 和 fi2 是否描述相同的文件。例如,在 Unix 上,这意味着两个基础结构的设备和 inode 字段是相同的; 在其他系统上,决策可以基于路径名称。 SameFile 仅适用于此包的统计信息返回的结果。在其他情况下它返回 false 。

func Setenv

func Setenv(key, value string) error

Setenv 设置由密钥命名的环境变量的值。它返回一个错误,如果有的话。

func Symlink

func Symlink(oldname, newname string) error

符号链接创建新名称作为旧名称的符号链接。如果有错误,它将是 * LinkError 类型。

func TempDir

func TempDir() string

TempDir 返回用于临时文件的默认目录。

在 Unix 系统上,如果非空则返回 $TMPDIR,否则返回 /tmp 。在 Windows 上,它使用 GetTempPath ,从%TMP%,%TEMP%,%USERPROFILE%或Windows目录中返回第一个非空值。在计划9中,它返回/ tmp。

该目录既不保证存在也不具有可访问的权限。

func Truncate

func Truncate(name string, size int64) error

截断更改指定文件的大小。如果文件是符号链接,它将更改链接目标的大小。如果有错误,它将是 * PathError 类型。

func Unsetenv

func Unsetenv(key string) error

Unsetenv 取消单个环境变量。

package mainimport ("os")func main() {
	os.Setenv("TMPDIR", "/my/tmp")
	defer os.Unsetenv("TMPDIR")}

type File

文件表示一个打开的文件描述符。

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

func Create

func Create(name string) (*File, error)

Create 使用模式0666(在 umask 之前)创建命名文件,如果它已经存在,则截断它。如果成功,返回文件上的方法可用于 I/O ; 关联的文件描述符具有模式 O_RDWR 。如果有错误,它将是 * PathError 类型。

func NewFile

func NewFile(fd uintptr, name string) *File

NewFile 使用给定的文件描述符和名称返回一个新的 File 。如果 fd 不是有效的文件描述符,则返回值为零。

func Open

func Open(name string) (*File, error)

打开打开指定文件以供阅读。如果成功,返回文件上的方法可用于读取; 关联的文件描述符具有模式 O_RDONLY 。如果有错误,它将是 * PathError 类型。

func OpenFile

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

OpenFile 是广义的公开呼叫;大多数用户将使用“打开”或“创建”。它打开具有指定标志(O_RDONLY等)和烫发(0666等)的指定文件(如果适用)。如果成功,返回文件上的方法可用于 I/O 。如果有错误,它将是 * PathError 类型。

package mainimport ("log""os")func main() {
	f, err := os.OpenFile("notes.txt", os.O_RDWR|os.O_CREATE, 0755)if err != nil {
		log.Fatal(err)}if err := f.Close(); err != nil {
		log.Fatal(err)}}

示例(追加)

package mainimport ("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 {
		log.Fatal(err)}if err := f.Close(); err != nil {
		log.Fatal(err)}}

func Pipe

func Pipe() (r *File, w *File, err error)

管道返回一对连接的文件; 从写入w的r个返回字节中读取。它返回文件和错误(如果有的话)。

func (*File) Chdir

func (f *File) Chdir() error

Chdir 将当前工作目录更改为文件,该文件必须是目录。如果有错误,它将是 * PathError 类型。

func (*File) Chmod

func (f *File) Chmod(mode FileMode) error

Chmod将文件的模式更改为模式。如果有错误,它将是* PathError类型。

func (*File) Chown

func (f *File) Chown(uid, gid int) error

Chown 更改指定文件的数字 uid 和 gid 。如果有错误,它将是 * PathError 类型。

在 Windows 上,它总是返回包装在 * PathError 中的 syscall.EWINDOWS 错误。

func (*File) Close

func (f *File) Close() error

关闭关闭文件,使其不能用于 I/O 。它返回一个错误,如果有的话。

func (*File) Fd

func (f *File) Fd() uintptr

Fd 返回引用打开文件的整数 Unix 文件描述符。文件描述符仅在 f.Close 被调用或f被垃圾收集之前有效。

func (*File) Name

func (f *File) Name() string

Name 返回提供给 Open 的文件的名称。

func (*File) Read

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

Read 从文件读取 len(b) 个字节。它返回读取的字节数和遇到的任何错误。在文件结尾,Read 返回0, io.EOF 。

func (*File) ReadAt

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

ReadAt 从文件开始以字节偏移关闭读取 len(b) 个字节。它返回读取的字节数和错误(如果有的话)。当 n <len(b) 时, ReadAt 总是返回非零错误。在文件结尾处,该错误是 io.EOF 。

func (*File) Readdir

func (f *File) Readdir(n int) ([]FileInfo, error)

Readdir 读取与文件关联的目录的内容,并以目录顺序返回最多 n 个 FileInfo 值的片段,Lstat 将返回该片段。随后对相同文件的调用将产生更多的 FileInfos 。

如果 n> 0,Readdir 最多返回 n 个 FileInfo 结构。在这种情况下,如果 Readdir 返回一个空片段,它将返回一个非零错误来解释原因。在目录结尾处,错误是 io.EOF 。

如果 n<=0,则 Readdir 从单个切片中的目录返回所有 FileInfo 。在这种情况下,如果 Readdir 成功(一直读取到目录的末尾),它将返回切片并返回一个零错误。如果在目录结束之前遇到错误,则 Readdir 将返回 FileInfo 读取直到该点,并出现非零错误。

func (*File) Readdirnames

func (f *File) Readdirnames(n int) (names []string, err error)

Readdirnames 读取并返回目录f中的一段名称。

如果 n>0,Readdirnames 最多返回 n 个名称。在这种情况下,如果 Readdirnames 返回一个空片段,它将返回一个非零错误来解释原因。在目录结尾处,错误是 io.EOF 。

如果n <= 0,则 Readdirnames 将返回单个切片中目录中的所有名称。在这种情况下,如果 Readdirnames 成功(一直读到目录的末尾),它将返回切片并返回一个零错误。如果在目录结束之前遇到错误,则 Readdirnames 将返回直到该点时读取的名称以及非零错误。

func (*File) Seek

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

Seek 将下一个 Read 或 Write on 文件的偏移量设置为偏移量,根据此解释:0表示相对于文件原点,1表示相对于当前偏移量,2表示相对于结束。它返回新的偏移量和一个错误,如果有的话。未指定使用 O_APPEND 打开的文件上的 Seek 行为。

func (*File) Stat

func (f *File) Stat() (FileInfo, error)

Stat 返回描述文件的 FileInfo 结构。如果有错误,它将是 * PathError 类型。

func (*File) Sync

func (f *File) Sync() error

同步将文件的当前内容提交到稳定存储。通常,这意味着将文件系统的最近写入数据的内存副本清除到磁盘。

func (*File) Truncate

func (f *File) Truncate(size int64) error

截断更改文件的大小。它不会更改 I/O 偏移量。如果有错误,它将是 * PathError 类型。

func (*File) Write

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

写入 len(b) 字节到文件。它返回写入的字节数和错误(如果有的话)。当 n!= len(b) 时,Write 返回非零错误。

func (*File) WriteAt

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

WriteAt 将 len(b) 个字节写入从字节偏移 off 开始的 File 。它返回写入的字节数和错误(如果有的话)。当 n!= len(b) 时,WriteAt 返回一个非零错误。

func (*File) WriteString

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

WriteString 就像 Write 一样,但是写入字符串s的内容而不是一个字节片段。

type FileInfo

FileInfo 描述一个文件,并由 Stat 和 Lstat 返回。

type FileInfo interface {        Name() string       // base name of the file        Size() int64        // length in bytes for regular files; system-dependent for others        Mode() FileMode     // file mode bits        ModTime() time.Time // modification time        IsDir() bool        // abbreviation for Mode().IsDir()        Sys() interface{}   // underlying data source (can return nil)}

func Lstat

func Lstat(name string) (FileInfo, error)

Lstat 返回一个描述指定文件的 FileInfo 。如果文件是符号链接,则返回的 FileInfo 描述符号链接。Lstat 不会尝试跟随链接。如果有错误,它将是 * PathError 类型。

func Stat

func Stat(name string) (FileInfo, error)

Stat 返回一个描述指定文件的 FileInfo 。如果有错误,它将是 * PathError 类型。

type FileMode

FileMode 表示文件的模式和权限位。这些位在所有系统上具有相同的定义,以便可以将有关文件的信息从一个系统移动到另一个系统。并非所有位都适用于所有系统。目录的唯一必需位是 ModeDir 。

type FileMode uint32

定义的文件模式位是 FileMode 的最高有效位。九个最低有效位是标准的 Unix rwxrwxrwx 权限。这些位的值应被视为公共 API 的一部分,并且可以用于有线协议或磁盘表示:尽管可能会添加新位,但不得更改它们。

const (        // The single letters are the abbreviations        // used by the String method's formatting.
        ModeDir        FileMode = 1 << (32 - 1 - iota) // d: is a directory
        ModeAppend                                     // a: append-only
        ModeExclusive                                  // l: exclusive use
        ModeTemporary                                  // T: temporary file; Plan 9 only
        ModeSymlink                                    // L: symbolic link
        ModeDevice                                     // D: device file
        ModeNamedPipe                                  // p: named pipe (FIFO)
        ModeSocket                                     // S: Unix domain socket
        ModeSetuid                                     // u: setuid
        ModeSetgid                                     // g: setgid
        ModeCharDevice                                 // c: Unix character device, when ModeDevice is set
        ModeSticky                                     // t: sticky        // Mask for the type bits. For regular files, none will be set.
        ModeType = ModeDir | ModeSymlink | ModeNamedPipe | ModeSocket | ModeDevice

        ModePerm FileMode = 0777 // Unix permission bits)

package mainimport ("fmt""log""os")func main() {
	fi, err := os.Lstat("some-filename")if err != nil {
		log.Fatal(err)}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")}}

func (FileMode) IsDir

func (m FileMode) IsDir() bool

IsDir 报告 m 是否描述目录。也就是说,它测试 ModeDir 位在 m 中设置。

func (FileMode) IsRegular

func (m FileMode) IsRegular() bool

IsRegular 报告 m 是否描述常规文件。也就是说,它测试没有设置模式类型位。

func (FileMode) Perm

func (m FileMode) Perm() FileMode

Perm 以 m 为单位返回 Unix 权限位。

func (FileMode) String

func (m FileMode) String() string

type LinkError

LinkError 在链接或符号链接期间记录错误或重命名系统调用以及导致它的路径。

type LinkError struct {
        Op  string
        Old string
        New string
        Err error}

func (*LinkError) Error

func (e *LinkError) Error() string

type PathError

PathError 记录错误以及导致它的操作和文件路径。

type PathError struct {
        Op   string
        Path string
        Err  error}

func (*PathError) Error

func (e *PathError) Error() string

type ProcAttr

ProcAttr 保存将应用于由 StartProcess 启动的新进程的属性。

type ProcAttr struct {        // If Dir is non-empty, the child changes into the directory before        // creating the process.
        Dir string        // If Env is non-nil, it gives the environment variables for the        // new process in the form returned by Environ.        // If it is nil, the result of Environ will be used.
        Env []string        // Files specifies the open files inherited by the new process. The        // first three entries correspond to standard input, standard output, and        // standard error. An implementation may support additional entries,        // depending on the underlying operating system. A nil entry corresponds        // to that file being closed when the process starts.
        Files []*File        // Operating system-specific process creation attributes.        // Note that setting this field means that your program        // may not execute properly or even compile on some        // operating systems.
        Sys *syscall.SysProcAttr}

type Process

进程存储有关由 StartProcess 创建的进程的信息。

type Process struct {
        Pid int        // contains filtered or unexported fields}

func FindProcess

func FindProcess(pid int) (*Process, error)

FindProcess 通过它的 pid 查找正在运行的进程。

它返回的进程可用于获取有关底层操作系统进程的信息。

在 Unix 系统上,无论过程是否存在,FindProcess 都会成功并为给定的 PID 返回一个 Process 。

func StartProcess

func StartProcess(name string, argv []string, attr *ProcAttr) (*Process, error)

StartProcess 使用由 name ,argv 和 attr 指定的程序,参数和属性启动一个新进程。

StartProcess 是一个低级别的界面。os/exec 软件包提供更高级的接口。

如果有错误,它将是 * PathError 类型。

func (*Process) Kill

func (p *Process) Kill() error

杀死导致进程立即退出。

func (*Process) Release

func (p *Process) Release() error

释放将释放与进程 p 关联的任何资源,以便将来无法使用。只有等待时才需要调用 Release 。

func (*Process) Signal

func (p *Process) Signal(sig Signal) error

信号向过程发送信号。未在Windows上发送中断。

func (*Process) Wait

func (p *Process) Wait() (*ProcessState, error)

等待进程退出,然后返回描述其状态和错误(如果有的话)的 ProcessState 。等待释放与流程相关的任何资源。在大多数操作系统上,进程必须是当前进程的子进程,否则将返回错误。

type ProcessState

ProcessState 存储有关由 Wait 报告的进程的信息。

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

func (*ProcessState) Exited

func (p *ProcessState) Exited() bool

已退出的报告是否已退出该程序。

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

成功报告程序是否成功退出,例如 Unix 上的退出状态为0。

func (*ProcessState) Sys

func (p *ProcessState) Sys() interface{}

Sys 返回有关该过程的系统相关退出信息。将其转换为适当的基础类型,例如 Unix 上的 syscall.WaitStatus 以访问其内容。

func (*ProcessState) SysUsage

func (p *ProcessState) SysUsage() interface{}

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 Signal

信号表示操作系统信号。通常的底层实现是操作系统相关的:在 Unix 上是 syscall.Signal 。

type Signal interface {        String() string        Signal() // to distinguish from other Stringers}

唯一保证在所有系统上存在的信号值是中断(发送进程中断)和终止(强制进程退出)。

var (
        Interrupt Signal = syscall.SIGINT
        Kill      Signal = syscall.SIGKILL)

type SyscallError

SyscallError 记录来自特定系统调用的错误。

type SyscallError struct {
        Syscall string
        Err     error}

func (*SyscallError) Error

func (e *SyscallError) Error() string
上一篇: 下一篇: