os

type file

File represents an open file descriptor(文件描述符,即句柄).File实现了 Reader & Writer

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

别忘了关闭文件/释放资源 defer f.Close()

API

  • func (f *File) Write(b []byte) (n int, err error):Write writes len(b) bytes 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 (f *File) WriteAt(b []byte, off int64) (n int, err 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. WriteAt returns a non-nil error when n != len(b).
  • func (f *File) WriteString(s string) (n int, err error):WriteString is like Write, but writes the contents of string s rather than a slice of bytes.
  • func (f *File) Read(b []byte) (n int, err error):Read reads up to len(b) bytes from the File. It returns the number of bytes read and any error encountered. At end of file, Read returns 0, io.EOF.
  • func (f *File) ReadAt(b []byte, off int64) (n int, err 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). At end of file, that error is io.EOF.
  • func (f *File) Readdir(n int) ([]FileInfo, error):Readdir reads the contents of the directory associated with file and returns a slice of up to n FileInfo values, as would be returned by Lstat, in directory order. Subsequent calls on the same file will yield further FileInfos.

    If n > 0, Readdir returns at most n FileInfo structures. In this case, if Readdir returns an empty slice, it will return a non-nil error explaining why. At the end of a directory, the error is io.EOF.

    If n <= 0, Readdir returns all the FileInfo from the directory in a single slice. In this case, if Readdir succeeds (reads all the way to the end of the directory), it returns the slice and a nil error. If it encounters an error before the end of the directory, Readdir returns the FileInfo read until that point and a non-nil error.
  • func (f *File) Readdirnames(n int) (names []string, err error):Readdirnames reads and returns a slice of names from the directory f.

    If n > 0, Readdirnames returns at most n names. In this case, if Readdirnames returns an empty slice, it will return a non-nil error explaining why. At the end of a directory, the error is io.EOF.

    If n <= 0, Readdirnames returns all the names from the directory in a single slice. In this case, if Readdirnames succeeds (reads all the way to the end of the directory), it returns the slice and a nil error. If it encounters an error before the end of the directory, Readdirnames returns the names read until that point and a non-nil error.

  • func Create(name string) (*File, error):Create creates the named file with mode 0666 (before umask), truncating it if it already exists. If successful, methods on the returned File can be used for I/O; the associated file descriptor has mode O_RDWR. If there is an error, it will be of type *PathError.

  • 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. If there is an error, it will be of type *PathError.

  • func (f *File) Close() error:Close closes the File, rendering it unusable for I/O. On files that support SetDeadline, any pending I/O operations will be canceled and return immediately with an error.
  • func (f *File) Chmod(mode FileMode) error:Chmod changes the mode of the file to mode. If there is an error, it will be of type *PathError.
  • func (f *File) Chown(uid, gid int) error:Chown changes the numeric uid and gid of the named file. If there is an error, it will be of type PathError.
    On Windows, it always returns the syscall.EWINDOWS error, wrapped in
    PathError.
  • func (f *File) Stat() (FileInfo, error):Stat returns the FileInfo structure describing file. If there is an error, it will be of type *PathError.
  • 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. If there is an error, it will be of type *PathError.
  • func Stat(name string) (FileInfo, error):Stat returns a FileInfo describing the named file. If there is an error, it will be of type *PathError. A FileInfo describes a file and is returned by Stat and 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)
    }
    
    FileInfo是个好东西,既可以拿来判断是否是directory,还可以获取文件的byte大小,配合buffer非常给力
  • 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.
  • func (f *File) Seek(offset int64, whence int) (ret int64, err error):Seek sets the offset for the next Read or Write on file to offset, interpreted according to whence: 0 means relative to the origin of the file, 1 means relative to the current offset, and 2 means relative to the end. It returns the new offset and an error, if any. The behavior of Seek on a file opened with O_APPEND is not specified.

  • func (f *File) Sync() error:Sync commits the current contents of the file to stable storage. Typically, this means flushing the file system's in-memory copy of recently written data to disk.

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

}
  • func Mkdir(name string, perm FileMode) error:Mkdir creates a new directory with the specified name and permission bits (before umask). If there is an error, it will be of type *PathError.
  • func MkdirAll(path string, perm FileMode) error:MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error. The permission bits perm (before umask) are used for all directories that MkdirAll creates. If path is already a directory, MkdirAll does nothing and returns nil.
  • func Readlink(name string) (string, error):Readlink returns the destination of the named symbolic link. If there is an error, it will be of type *PathError.
  • func Remove(name string) error:Remove removes the named file or (empty) directory. If there is an error, it will be of type *PathError.
  • func RemoveAll(path string) error:RemoveAll removes path and any children it contains. It removes everything it can but returns the first error it encounters. If the path does not exist, RemoveAll returns nil (no error). If there is an error, it will be of type *PathError.
  • func Rename(oldpath, newpath string) error:Rename renames (moves) oldpath to newpath. If newpath already exists and is not a directory, Rename replaces it. OS-specific restrictions may apply when oldpath and newpath are in different directories. If there is an error, it will be of type *LinkError.
  • 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; on other systems the decision may be based on the path names. SameFile only applies to results returned by this package's Stat. It returns false in other cases.
  • 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. If there is an error, it will be of type *LinkError.

  • func TempDir() string: TempDir returns the default directory to use for temporary files.
    On Unix systems, it returns $TMPDIR if non-empty, else /tmp. On Windows, it uses GetTempPath, returning the first non-empty value from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory. On Plan 9, it returns /tmp.

    The directory is neither guaranteed to exist nor have accessible permissions.

  • 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. If there is an error, it will be of type *PathError.

  • func Unsetenv(key string) error:Unsetenv unsets a single environment variable.

  • func (m FileMode) IsDir() bool:IsDir reports whether m describes a directory. That is, it tests for the ModeDir bit being set in m.

  • func (m FileMode) IsRegular() bool:IsRegular reports whether m describes a regular file. That is, it tests that no mode type bits are set.
  • func (m FileMode) Perm() FileMode:Perm returns the Unix permission bits in m.
  • func (m FileMode) String() string
  • func MkdirAll(path string, perm FileMode) error:MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error. The permission bits perm (before umask) are used for all directories that MkdirAll creates. If path is already a directory, MkdirAll does nothing and returns nil.
  • func Pipe() (r *File, w *File, err error):Pipe returns a connected pair of Files; reads from r return bytes written to w. It returns the files and an error, if any.

    type FileMode

    A 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. Not all bits apply to all systems. The only required bit is ModeDir for directories.

  • func UserCacheDir() (string, error):UserCacheDir returns the default root directory to use for user-specific cached data. Users should create their own application-specific subdirectory within this one and use that.

    On Unix systems, it returns $XDG_CACHE_HOME as specified by https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html if non-empty, else $HOME/.cache. On Darwin, it returns $HOME/Library/Caches. On Windows, it returns %LocalAppData%. On Plan 9, it returns $home/lib/cache.

    If the location cannot be determined (for example, $HOME is not defined), then it will return an error.

  • func UserHomeDir() (string, error):UserHomeDir returns the current user's home directory.

    On Unix, including macOS, it returns the $HOME environment variable. On Windows, it returns %USERPROFILE%. On Plan 9, it returns the $home environment variable.
type FileMode uint32


The defined file mode bits are the most significant bits of the FileMode. The nine least-significant bits are the standard Unix rwxrwxrwx permissions. The values of these bits should be considered part of the public API and may be used in wire protocols or disk representations: they must not be changed, although new bits might be added.

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
        ModeIrregular                                  // ?: non-regular file; nothing else is known about this file

        // Mask for the type bits. For regular files, none will be set.
        ModeType = ModeDir | ModeSymlink | ModeNamedPipe | ModeSocket | ModeDevice | ModeCharDevice | ModeIrregular

        ModePerm FileMode = 0777 // Unix permission bits
)
package main

import (
    "fmt"
    "log"
    "os"
)

func main() {
    fi, err := os.Lstat("some-filename")
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("permissions: %#o\n", fi.Mode().Perm()) // 0400, 0777, 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")
    }
}

results matching ""

    No results matching ""