Source file src/os/file.go

Documentation: os

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package os provides a platform-independent interface to operating system
     6  // functionality. The design is Unix-like, although the error handling is
     7  // Go-like; failing calls return values of type error rather than error numbers.
     8  // Often, more information is available within the error. For example,
     9  // if a call that takes a file name fails, such as Open or Stat, the error
    10  // will include the failing file name when printed and will be of type
    11  // *PathError, which may be unpacked for more information.
    12  //
    13  // The os interface is intended to be uniform across all operating systems.
    14  // Features not generally available appear in the system-specific package syscall.
    15  //
    16  // Here is a simple example, opening a file and reading some of it.
    17  //
    18  //	file, err := os.Open("file.go") // For read access.
    19  //	if err != nil {
    20  //		log.Fatal(err)
    21  //	}
    22  //
    23  // If the open fails, the error string will be self-explanatory, like
    24  //
    25  //	open file.go: no such file or directory
    26  //
    27  // The file's data can then be read into a slice of bytes. Read and
    28  // Write take their byte counts from the length of the argument slice.
    29  //
    30  //	data := make([]byte, 100)
    31  //	count, err := file.Read(data)
    32  //	if err != nil {
    33  //		log.Fatal(err)
    34  //	}
    35  //	fmt.Printf("read %d bytes: %q\n", count, data[:count])
    36  //
    37  // Note: The maximum number of concurrent operations on a File may be limited by
    38  // the OS or the system. The number should be high, but exceeding it may degrade
    39  // performance or cause other issues.
    40  //
    41  package os
    42  
    43  import (
    44  	"errors"
    45  	"internal/poll"
    46  	"internal/testlog"
    47  	"io"
    48  	"runtime"
    49  	"syscall"
    50  	"time"
    51  )
    52  
    53  // Name returns the name of the file as presented to Open.
    54  func (f *File) Name() string { return f.name }
    55  
    56  // Stdin, Stdout, and Stderr are open Files pointing to the standard input,
    57  // standard output, and standard error file descriptors.
    58  //
    59  // Note that the Go runtime writes to standard error for panics and crashes;
    60  // closing Stderr may cause those messages to go elsewhere, perhaps
    61  // to a file opened later.
    62  var (
    63  	Stdin  = NewFile(uintptr(syscall.Stdin), "/dev/stdin")
    64  	Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout")
    65  	Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr")
    66  )
    67  
    68  // Flags to OpenFile wrapping those of the underlying system. Not all
    69  // flags may be implemented on a given system.
    70  const (
    71  	// Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
    72  	O_RDONLY int = syscall.O_RDONLY // open the file read-only.
    73  	O_WRONLY int = syscall.O_WRONLY // open the file write-only.
    74  	O_RDWR   int = syscall.O_RDWR   // open the file read-write.
    75  	// The remaining values may be or'ed in to control behavior.
    76  	O_APPEND int = syscall.O_APPEND // append data to the file when writing.
    77  	O_CREATE int = syscall.O_CREAT  // create a new file if none exists.
    78  	O_EXCL   int = syscall.O_EXCL   // used with O_CREATE, file must not exist.
    79  	O_SYNC   int = syscall.O_SYNC   // open for synchronous I/O.
    80  	O_TRUNC  int = syscall.O_TRUNC  // truncate regular writable file when opened.
    81  )
    82  
    83  // Seek whence values.
    84  //
    85  // Deprecated: Use io.SeekStart, io.SeekCurrent, and io.SeekEnd.
    86  const (
    87  	SEEK_SET int = 0 // seek relative to the origin of the file
    88  	SEEK_CUR int = 1 // seek relative to the current offset
    89  	SEEK_END int = 2 // seek relative to the end
    90  )
    91  
    92  // LinkError records an error during a link or symlink or rename
    93  // system call and the paths that caused it.
    94  type LinkError struct {
    95  	Op  string
    96  	Old string
    97  	New string
    98  	Err error
    99  }
   100  
   101  func (e *LinkError) Error() string {
   102  	return e.Op + " " + e.Old + " " + e.New + ": " + e.Err.Error()
   103  }
   104  
   105  func (e *LinkError) Unwrap() error {
   106  	return e.Err
   107  }
   108  
   109  // Read reads up to len(b) bytes from the File.
   110  // It returns the number of bytes read and any error encountered.
   111  // At end of file, Read returns 0, io.EOF.
   112  func (f *File) Read(b []byte) (n int, err error) {
   113  	if err := f.checkValid("read"); err != nil {
   114  		return 0, err
   115  	}
   116  	n, e := f.read(b)
   117  	return n, f.wrapErr("read", e)
   118  }
   119  
   120  // ReadAt reads len(b) bytes from the File starting at byte offset off.
   121  // It returns the number of bytes read and the error, if any.
   122  // ReadAt always returns a non-nil error when n < len(b).
   123  // At end of file, that error is io.EOF.
   124  func (f *File) ReadAt(b []byte, off int64) (n int, err error) {
   125  	if err := f.checkValid("read"); err != nil {
   126  		return 0, err
   127  	}
   128  
   129  	if off < 0 {
   130  		return 0, &PathError{"readat", f.name, errors.New("negative offset")}
   131  	}
   132  
   133  	for len(b) > 0 {
   134  		m, e := f.pread(b, off)
   135  		if e != nil {
   136  			err = f.wrapErr("read", e)
   137  			break
   138  		}
   139  		n += m
   140  		b = b[m:]
   141  		off += int64(m)
   142  	}
   143  	return
   144  }
   145  
   146  // Write writes len(b) bytes to the File.
   147  // It returns the number of bytes written and an error, if any.
   148  // Write returns a non-nil error when n != len(b).
   149  func (f *File) Write(b []byte) (n int, err error) {
   150  	if err := f.checkValid("write"); err != nil {
   151  		return 0, err
   152  	}
   153  	n, e := f.write(b)
   154  	if n < 0 {
   155  		n = 0
   156  	}
   157  	if n != len(b) {
   158  		err = io.ErrShortWrite
   159  	}
   160  
   161  	epipecheck(f, e)
   162  
   163  	if e != nil {
   164  		err = f.wrapErr("write", e)
   165  	}
   166  
   167  	return n, err
   168  }
   169  
   170  var errWriteAtInAppendMode = errors.New("os: invalid use of WriteAt on file opened with O_APPEND")
   171  
   172  // WriteAt writes len(b) bytes to the File starting at byte offset off.
   173  // It returns the number of bytes written and an error, if any.
   174  // WriteAt returns a non-nil error when n != len(b).
   175  //
   176  // If file was opened with the O_APPEND flag, WriteAt returns an error.
   177  func (f *File) WriteAt(b []byte, off int64) (n int, err error) {
   178  	if err := f.checkValid("write"); err != nil {
   179  		return 0, err
   180  	}
   181  	if f.appendMode {
   182  		return 0, errWriteAtInAppendMode
   183  	}
   184  
   185  	if off < 0 {
   186  		return 0, &PathError{"writeat", f.name, errors.New("negative offset")}
   187  	}
   188  
   189  	for len(b) > 0 {
   190  		m, e := f.pwrite(b, off)
   191  		if e != nil {
   192  			err = f.wrapErr("write", e)
   193  			break
   194  		}
   195  		n += m
   196  		b = b[m:]
   197  		off += int64(m)
   198  	}
   199  	return
   200  }
   201  
   202  // Seek sets the offset for the next Read or Write on file to offset, interpreted
   203  // according to whence: 0 means relative to the origin of the file, 1 means
   204  // relative to the current offset, and 2 means relative to the end.
   205  // It returns the new offset and an error, if any.
   206  // The behavior of Seek on a file opened with O_APPEND is not specified.
   207  func (f *File) Seek(offset int64, whence int) (ret int64, err error) {
   208  	if err := f.checkValid("seek"); err != nil {
   209  		return 0, err
   210  	}
   211  	r, e := f.seek(offset, whence)
   212  	if e == nil && f.dirinfo != nil && r != 0 {
   213  		e = syscall.EISDIR
   214  	}
   215  	if e != nil {
   216  		return 0, f.wrapErr("seek", e)
   217  	}
   218  	return r, nil
   219  }
   220  
   221  // WriteString is like Write, but writes the contents of string s rather than
   222  // a slice of bytes.
   223  func (f *File) WriteString(s string) (n int, err error) {
   224  	return f.Write([]byte(s))
   225  }
   226  
   227  // Mkdir creates a new directory with the specified name and permission
   228  // bits (before umask).
   229  // If there is an error, it will be of type *PathError.
   230  func Mkdir(name string, perm FileMode) error {
   231  	e := syscall.Mkdir(fixLongPath(name), syscallMode(perm))
   232  
   233  	if e != nil {
   234  		return &PathError{"mkdir", name, e}
   235  	}
   236  
   237  	// mkdir(2) itself won't handle the sticky bit on *BSD and Solaris
   238  	if !supportsCreateWithStickyBit && perm&ModeSticky != 0 {
   239  		e = setStickyBit(name)
   240  
   241  		if e != nil {
   242  			Remove(name)
   243  			return e
   244  		}
   245  	}
   246  
   247  	return nil
   248  }
   249  
   250  // setStickyBit adds ModeSticky to the permision bits of path, non atomic.
   251  func setStickyBit(name string) error {
   252  	fi, err := Stat(name)
   253  	if err != nil {
   254  		return err
   255  	}
   256  	return Chmod(name, fi.Mode()|ModeSticky)
   257  }
   258  
   259  // Chdir changes the current working directory to the named directory.
   260  // If there is an error, it will be of type *PathError.
   261  func Chdir(dir string) error {
   262  	if e := syscall.Chdir(dir); e != nil {
   263  		testlog.Open(dir) // observe likely non-existent directory
   264  		return &PathError{"chdir", dir, e}
   265  	}
   266  	if log := testlog.Logger(); log != nil {
   267  		wd, err := Getwd()
   268  		if err == nil {
   269  			log.Chdir(wd)
   270  		}
   271  	}
   272  	return nil
   273  }
   274  
   275  // Open opens the named file for reading. If successful, methods on
   276  // the returned file can be used for reading; the associated file
   277  // descriptor has mode O_RDONLY.
   278  // If there is an error, it will be of type *PathError.
   279  func Open(name string) (*File, error) {
   280  	return OpenFile(name, O_RDONLY, 0)
   281  }
   282  
   283  // Create creates or truncates the named file. If the file already exists,
   284  // it is truncated. If the file does not exist, it is created with mode 0666
   285  // (before umask). If successful, methods on the returned File can
   286  // be used for I/O; the associated file descriptor has mode O_RDWR.
   287  // If there is an error, it will be of type *PathError.
   288  func Create(name string) (*File, error) {
   289  	return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666)
   290  }
   291  
   292  // OpenFile is the generalized open call; most users will use Open
   293  // or Create instead. It opens the named file with specified flag
   294  // (O_RDONLY etc.). If the file does not exist, and the O_CREATE flag
   295  // is passed, it is created with mode perm (before umask). If successful,
   296  // methods on the returned File can be used for I/O.
   297  // If there is an error, it will be of type *PathError.
   298  func OpenFile(name string, flag int, perm FileMode) (*File, error) {
   299  	testlog.Open(name)
   300  	f, err := openFileNolog(name, flag, perm)
   301  	if err != nil {
   302  		return nil, err
   303  	}
   304  	f.appendMode = flag&O_APPEND != 0
   305  
   306  	return f, nil
   307  }
   308  
   309  // lstat is overridden in tests.
   310  var lstat = Lstat
   311  
   312  // Rename renames (moves) oldpath to newpath.
   313  // If newpath already exists and is not a directory, Rename replaces it.
   314  // OS-specific restrictions may apply when oldpath and newpath are in different directories.
   315  // If there is an error, it will be of type *LinkError.
   316  func Rename(oldpath, newpath string) error {
   317  	return rename(oldpath, newpath)
   318  }
   319  
   320  // Many functions in package syscall return a count of -1 instead of 0.
   321  // Using fixCount(call()) instead of call() corrects the count.
   322  func fixCount(n int, err error) (int, error) {
   323  	if n < 0 {
   324  		n = 0
   325  	}
   326  	return n, err
   327  }
   328  
   329  // wrapErr wraps an error that occurred during an operation on an open file.
   330  // It passes io.EOF through unchanged, otherwise converts
   331  // poll.ErrFileClosing to ErrClosed and wraps the error in a PathError.
   332  func (f *File) wrapErr(op string, err error) error {
   333  	if err == nil || err == io.EOF {
   334  		return err
   335  	}
   336  	if err == poll.ErrFileClosing {
   337  		err = ErrClosed
   338  	}
   339  	return &PathError{op, f.name, err}
   340  }
   341  
   342  // TempDir returns the default directory to use for temporary files.
   343  //
   344  // On Unix systems, it returns $TMPDIR if non-empty, else /tmp.
   345  // On Windows, it uses GetTempPath, returning the first non-empty
   346  // value from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory.
   347  // On Plan 9, it returns /tmp.
   348  //
   349  // The directory is neither guaranteed to exist nor have accessible
   350  // permissions.
   351  func TempDir() string {
   352  	return tempDir()
   353  }
   354  
   355  // UserCacheDir returns the default root directory to use for user-specific
   356  // cached data. Users should create their own application-specific subdirectory
   357  // within this one and use that.
   358  //
   359  // On Unix systems, it returns $XDG_CACHE_HOME as specified by
   360  // https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html if
   361  // non-empty, else $HOME/.cache.
   362  // On Darwin, it returns $HOME/Library/Caches.
   363  // On Windows, it returns %LocalAppData%.
   364  // On Plan 9, it returns $home/lib/cache.
   365  //
   366  // If the location cannot be determined (for example, $HOME is not defined),
   367  // then it will return an error.
   368  func UserCacheDir() (string, error) {
   369  	var dir string
   370  
   371  	switch runtime.GOOS {
   372  	case "windows":
   373  		dir = Getenv("LocalAppData")
   374  		if dir == "" {
   375  			return "", errors.New("%LocalAppData% is not defined")
   376  		}
   377  
   378  	case "darwin":
   379  		dir = Getenv("HOME")
   380  		if dir == "" {
   381  			return "", errors.New("$HOME is not defined")
   382  		}
   383  		dir += "/Library/Caches"
   384  
   385  	case "plan9":
   386  		dir = Getenv("home")
   387  		if dir == "" {
   388  			return "", errors.New("$home is not defined")
   389  		}
   390  		dir += "/lib/cache"
   391  
   392  	default: // Unix
   393  		dir = Getenv("XDG_CACHE_HOME")
   394  		if dir == "" {
   395  			dir = Getenv("HOME")
   396  			if dir == "" {
   397  				return "", errors.New("neither $XDG_CACHE_HOME nor $HOME are defined")
   398  			}
   399  			dir += "/.cache"
   400  		}
   401  	}
   402  
   403  	return dir, nil
   404  }
   405  
   406  // UserConfigDir returns the default root directory to use for user-specific
   407  // configuration data. Users should create their own application-specific
   408  // subdirectory within this one and use that.
   409  //
   410  // On Unix systems, it returns $XDG_CONFIG_HOME as specified by
   411  // https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html if
   412  // non-empty, else $HOME/.config.
   413  // On Darwin, it returns $HOME/Library/Application Support.
   414  // On Windows, it returns %AppData%.
   415  // On Plan 9, it returns $home/lib.
   416  //
   417  // If the location cannot be determined (for example, $HOME is not defined),
   418  // then it will return an error.
   419  func UserConfigDir() (string, error) {
   420  	var dir string
   421  
   422  	switch runtime.GOOS {
   423  	case "windows":
   424  		dir = Getenv("AppData")
   425  		if dir == "" {
   426  			return "", errors.New("%AppData% is not defined")
   427  		}
   428  
   429  	case "darwin":
   430  		dir = Getenv("HOME")
   431  		if dir == "" {
   432  			return "", errors.New("$HOME is not defined")
   433  		}
   434  		dir += "/Library/Application Support"
   435  
   436  	case "plan9":
   437  		dir = Getenv("home")
   438  		if dir == "" {
   439  			return "", errors.New("$home is not defined")
   440  		}
   441  		dir += "/lib"
   442  
   443  	default: // Unix
   444  		dir = Getenv("XDG_CONFIG_HOME")
   445  		if dir == "" {
   446  			dir = Getenv("HOME")
   447  			if dir == "" {
   448  				return "", errors.New("neither $XDG_CONFIG_HOME nor $HOME are defined")
   449  			}
   450  			dir += "/.config"
   451  		}
   452  	}
   453  
   454  	return dir, nil
   455  }
   456  
   457  // UserHomeDir returns the current user's home directory.
   458  //
   459  // On Unix, including macOS, it returns the $HOME environment variable.
   460  // On Windows, it returns %USERPROFILE%.
   461  // On Plan 9, it returns the $home environment variable.
   462  func UserHomeDir() (string, error) {
   463  	env, enverr := "HOME", "$HOME"
   464  	switch runtime.GOOS {
   465  	case "windows":
   466  		env, enverr = "USERPROFILE", "%userprofile%"
   467  	case "plan9":
   468  		env, enverr = "home", "$home"
   469  	}
   470  	if v := Getenv(env); v != "" {
   471  		return v, nil
   472  	}
   473  	// On some geese the home directory is not always defined.
   474  	switch runtime.GOOS {
   475  	case "nacl":
   476  		return "/", nil
   477  	case "android":
   478  		return "/sdcard", nil
   479  	case "darwin":
   480  		if runtime.GOARCH == "arm" || runtime.GOARCH == "arm64" {
   481  			return "/", nil
   482  		}
   483  	}
   484  	return "", errors.New(enverr + " is not defined")
   485  }
   486  
   487  // Chmod changes the mode of the named file to mode.
   488  // If the file is a symbolic link, it changes the mode of the link's target.
   489  // If there is an error, it will be of type *PathError.
   490  //
   491  // A different subset of the mode bits are used, depending on the
   492  // operating system.
   493  //
   494  // On Unix, the mode's permission bits, ModeSetuid, ModeSetgid, and
   495  // ModeSticky are used.
   496  //
   497  // On Windows, only the 0200 bit (owner writable) of mode is used; it
   498  // controls whether the file's read-only attribute is set or cleared.
   499  // The other bits are currently unused. For compatibility with Go 1.12
   500  // and earlier, use a non-zero mode. Use mode 0400 for a read-only
   501  // file and 0600 for a readable+writable file.
   502  //
   503  // On Plan 9, the mode's permission bits, ModeAppend, ModeExclusive,
   504  // and ModeTemporary are used.
   505  func Chmod(name string, mode FileMode) error { return chmod(name, mode) }
   506  
   507  // Chmod changes the mode of the file to mode.
   508  // If there is an error, it will be of type *PathError.
   509  func (f *File) Chmod(mode FileMode) error { return f.chmod(mode) }
   510  
   511  // SetDeadline sets the read and write deadlines for a File.
   512  // It is equivalent to calling both SetReadDeadline and SetWriteDeadline.
   513  //
   514  // Only some kinds of files support setting a deadline. Calls to SetDeadline
   515  // for files that do not support deadlines will return ErrNoDeadline.
   516  // On most systems ordinary files do not support deadlines, but pipes do.
   517  //
   518  // A deadline is an absolute time after which I/O operations fail with an
   519  // error instead of blocking. The deadline applies to all future and pending
   520  // I/O, not just the immediately following call to Read or Write.
   521  // After a deadline has been exceeded, the connection can be refreshed
   522  // by setting a deadline in the future.
   523  //
   524  // An error returned after a timeout fails will implement the
   525  // Timeout method, and calling the Timeout method will return true.
   526  // The PathError and SyscallError types implement the Timeout method.
   527  // In general, call IsTimeout to test whether an error indicates a timeout.
   528  //
   529  // An idle timeout can be implemented by repeatedly extending
   530  // the deadline after successful Read or Write calls.
   531  //
   532  // A zero value for t means I/O operations will not time out.
   533  func (f *File) SetDeadline(t time.Time) error {
   534  	return f.setDeadline(t)
   535  }
   536  
   537  // SetReadDeadline sets the deadline for future Read calls and any
   538  // currently-blocked Read call.
   539  // A zero value for t means Read will not time out.
   540  // Not all files support setting deadlines; see SetDeadline.
   541  func (f *File) SetReadDeadline(t time.Time) error {
   542  	return f.setReadDeadline(t)
   543  }
   544  
   545  // SetWriteDeadline sets the deadline for any future Write calls and any
   546  // currently-blocked Write call.
   547  // Even if Write times out, it may return n > 0, indicating that
   548  // some of the data was successfully written.
   549  // A zero value for t means Write will not time out.
   550  // Not all files support setting deadlines; see SetDeadline.
   551  func (f *File) SetWriteDeadline(t time.Time) error {
   552  	return f.setWriteDeadline(t)
   553  }
   554  
   555  // SyscallConn returns a raw file.
   556  // This implements the syscall.Conn interface.
   557  func (f *File) SyscallConn() (syscall.RawConn, error) {
   558  	if err := f.checkValid("SyscallConn"); err != nil {
   559  		return nil, err
   560  	}
   561  	return newRawConn(f)
   562  }
   563  

View as plain text