Source file src/os/file.go

     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  package os
    41  
    42  import (
    43  	"errors"
    44  	"internal/poll"
    45  	"internal/safefilepath"
    46  	"internal/testlog"
    47  	"io"
    48  	"io/fs"
    49  	"runtime"
    50  	"syscall"
    51  	"time"
    52  	"unsafe"
    53  )
    54  
    55  // Name returns the name of the file as presented to Open.
    56  func (f *File) Name() string { return f.name }
    57  
    58  // Stdin, Stdout, and Stderr are open Files pointing to the standard input,
    59  // standard output, and standard error file descriptors.
    60  //
    61  // Note that the Go runtime writes to standard error for panics and crashes;
    62  // closing Stderr may cause those messages to go elsewhere, perhaps
    63  // to a file opened later.
    64  var (
    65  	Stdin  = NewFile(uintptr(syscall.Stdin), "/dev/stdin")
    66  	Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout")
    67  	Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr")
    68  )
    69  
    70  // Flags to OpenFile wrapping those of the underlying system. Not all
    71  // flags may be implemented on a given system.
    72  const (
    73  	// Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
    74  	O_RDONLY int = syscall.O_RDONLY // open the file read-only.
    75  	O_WRONLY int = syscall.O_WRONLY // open the file write-only.
    76  	O_RDWR   int = syscall.O_RDWR   // open the file read-write.
    77  	// The remaining values may be or'ed in to control behavior.
    78  	O_APPEND int = syscall.O_APPEND // append data to the file when writing.
    79  	O_CREATE int = syscall.O_CREAT  // create a new file if none exists.
    80  	O_EXCL   int = syscall.O_EXCL   // used with O_CREATE, file must not exist.
    81  	O_SYNC   int = syscall.O_SYNC   // open for synchronous I/O.
    82  	O_TRUNC  int = syscall.O_TRUNC  // truncate regular writable file when opened.
    83  )
    84  
    85  // Seek whence values.
    86  //
    87  // Deprecated: Use io.SeekStart, io.SeekCurrent, and io.SeekEnd.
    88  const (
    89  	SEEK_SET int = 0 // seek relative to the origin of the file
    90  	SEEK_CUR int = 1 // seek relative to the current offset
    91  	SEEK_END int = 2 // seek relative to the end
    92  )
    93  
    94  // LinkError records an error during a link or symlink or rename
    95  // system call and the paths that caused it.
    96  type LinkError struct {
    97  	Op  string
    98  	Old string
    99  	New string
   100  	Err error
   101  }
   102  
   103  func (e *LinkError) Error() string {
   104  	return e.Op + " " + e.Old + " " + e.New + ": " + e.Err.Error()
   105  }
   106  
   107  func (e *LinkError) Unwrap() error {
   108  	return e.Err
   109  }
   110  
   111  // Read reads up to len(b) bytes from the File and stores them in b.
   112  // It returns the number of bytes read and any error encountered.
   113  // At end of file, Read returns 0, io.EOF.
   114  func (f *File) Read(b []byte) (n int, err error) {
   115  	if err := f.checkValid("read"); err != nil {
   116  		return 0, err
   117  	}
   118  	n, e := f.read(b)
   119  	return n, f.wrapErr("read", e)
   120  }
   121  
   122  // ReadAt reads len(b) bytes from the File starting at byte offset off.
   123  // It returns the number of bytes read and the error, if any.
   124  // ReadAt always returns a non-nil error when n < len(b).
   125  // At end of file, that error is io.EOF.
   126  func (f *File) ReadAt(b []byte, off int64) (n int, err error) {
   127  	if err := f.checkValid("read"); err != nil {
   128  		return 0, err
   129  	}
   130  
   131  	if off < 0 {
   132  		return 0, &PathError{Op: "readat", Path: f.name, Err: errors.New("negative offset")}
   133  	}
   134  
   135  	for len(b) > 0 {
   136  		m, e := f.pread(b, off)
   137  		if e != nil {
   138  			err = f.wrapErr("read", e)
   139  			break
   140  		}
   141  		n += m
   142  		b = b[m:]
   143  		off += int64(m)
   144  	}
   145  	return
   146  }
   147  
   148  // ReadFrom implements io.ReaderFrom.
   149  func (f *File) ReadFrom(r io.Reader) (n int64, err error) {
   150  	if err := f.checkValid("write"); err != nil {
   151  		return 0, err
   152  	}
   153  	n, handled, e := f.readFrom(r)
   154  	if !handled {
   155  		return genericReadFrom(f, r) // without wrapping
   156  	}
   157  	return n, f.wrapErr("write", e)
   158  }
   159  
   160  // noReadFrom can be embedded alongside another type to
   161  // hide the ReadFrom method of that other type.
   162  type noReadFrom struct{}
   163  
   164  // ReadFrom hides another ReadFrom method.
   165  // It should never be called.
   166  func (noReadFrom) ReadFrom(io.Reader) (int64, error) {
   167  	panic("can't happen")
   168  }
   169  
   170  // fileWithoutReadFrom implements all the methods of *File other
   171  // than ReadFrom. This is used to permit ReadFrom to call io.Copy
   172  // without leading to a recursive call to ReadFrom.
   173  type fileWithoutReadFrom struct {
   174  	noReadFrom
   175  	*File
   176  }
   177  
   178  func genericReadFrom(f *File, r io.Reader) (int64, error) {
   179  	return io.Copy(fileWithoutReadFrom{File: f}, r)
   180  }
   181  
   182  // Write writes len(b) bytes from b to the File.
   183  // It returns the number of bytes written and an error, if any.
   184  // Write returns a non-nil error when n != len(b).
   185  func (f *File) Write(b []byte) (n int, err error) {
   186  	if err := f.checkValid("write"); err != nil {
   187  		return 0, err
   188  	}
   189  	n, e := f.write(b)
   190  	if n < 0 {
   191  		n = 0
   192  	}
   193  	if n != len(b) {
   194  		err = io.ErrShortWrite
   195  	}
   196  
   197  	epipecheck(f, e)
   198  
   199  	if e != nil {
   200  		err = f.wrapErr("write", e)
   201  	}
   202  
   203  	return n, err
   204  }
   205  
   206  var errWriteAtInAppendMode = errors.New("os: invalid use of WriteAt on file opened with O_APPEND")
   207  
   208  // WriteAt writes len(b) bytes to the File starting at byte offset off.
   209  // It returns the number of bytes written and an error, if any.
   210  // WriteAt returns a non-nil error when n != len(b).
   211  //
   212  // If file was opened with the O_APPEND flag, WriteAt returns an error.
   213  func (f *File) WriteAt(b []byte, off int64) (n int, err error) {
   214  	if err := f.checkValid("write"); err != nil {
   215  		return 0, err
   216  	}
   217  	if f.appendMode {
   218  		return 0, errWriteAtInAppendMode
   219  	}
   220  
   221  	if off < 0 {
   222  		return 0, &PathError{Op: "writeat", Path: f.name, Err: errors.New("negative offset")}
   223  	}
   224  
   225  	for len(b) > 0 {
   226  		m, e := f.pwrite(b, off)
   227  		if e != nil {
   228  			err = f.wrapErr("write", e)
   229  			break
   230  		}
   231  		n += m
   232  		b = b[m:]
   233  		off += int64(m)
   234  	}
   235  	return
   236  }
   237  
   238  // WriteTo implements io.WriterTo.
   239  func (f *File) WriteTo(w io.Writer) (n int64, err error) {
   240  	if err := f.checkValid("read"); err != nil {
   241  		return 0, err
   242  	}
   243  	n, handled, e := f.writeTo(w)
   244  	if handled {
   245  		return n, f.wrapErr("read", e)
   246  	}
   247  	return genericWriteTo(f, w) // without wrapping
   248  }
   249  
   250  // noWriteTo can be embedded alongside another type to
   251  // hide the WriteTo method of that other type.
   252  type noWriteTo struct{}
   253  
   254  // WriteTo hides another WriteTo method.
   255  // It should never be called.
   256  func (noWriteTo) WriteTo(io.Writer) (int64, error) {
   257  	panic("can't happen")
   258  }
   259  
   260  // fileWithoutWriteTo implements all the methods of *File other
   261  // than WriteTo. This is used to permit WriteTo to call io.Copy
   262  // without leading to a recursive call to WriteTo.
   263  type fileWithoutWriteTo struct {
   264  	noWriteTo
   265  	*File
   266  }
   267  
   268  func genericWriteTo(f *File, w io.Writer) (int64, error) {
   269  	return io.Copy(w, fileWithoutWriteTo{File: f})
   270  }
   271  
   272  // Seek sets the offset for the next Read or Write on file to offset, interpreted
   273  // according to whence: 0 means relative to the origin of the file, 1 means
   274  // relative to the current offset, and 2 means relative to the end.
   275  // It returns the new offset and an error, if any.
   276  // The behavior of Seek on a file opened with O_APPEND is not specified.
   277  func (f *File) Seek(offset int64, whence int) (ret int64, err error) {
   278  	if err := f.checkValid("seek"); err != nil {
   279  		return 0, err
   280  	}
   281  	r, e := f.seek(offset, whence)
   282  	if e == nil && f.dirinfo != nil && r != 0 {
   283  		e = syscall.EISDIR
   284  	}
   285  	if e != nil {
   286  		return 0, f.wrapErr("seek", e)
   287  	}
   288  	return r, nil
   289  }
   290  
   291  // WriteString is like Write, but writes the contents of string s rather than
   292  // a slice of bytes.
   293  func (f *File) WriteString(s string) (n int, err error) {
   294  	b := unsafe.Slice(unsafe.StringData(s), len(s))
   295  	return f.Write(b)
   296  }
   297  
   298  // Mkdir creates a new directory with the specified name and permission
   299  // bits (before umask).
   300  // If there is an error, it will be of type *PathError.
   301  func Mkdir(name string, perm FileMode) error {
   302  	longName := fixLongPath(name)
   303  	e := ignoringEINTR(func() error {
   304  		return syscall.Mkdir(longName, syscallMode(perm))
   305  	})
   306  
   307  	if e != nil {
   308  		return &PathError{Op: "mkdir", Path: name, Err: e}
   309  	}
   310  
   311  	// mkdir(2) itself won't handle the sticky bit on *BSD and Solaris
   312  	if !supportsCreateWithStickyBit && perm&ModeSticky != 0 {
   313  		e = setStickyBit(name)
   314  
   315  		if e != nil {
   316  			Remove(name)
   317  			return e
   318  		}
   319  	}
   320  
   321  	return nil
   322  }
   323  
   324  // setStickyBit adds ModeSticky to the permission bits of path, non atomic.
   325  func setStickyBit(name string) error {
   326  	fi, err := Stat(name)
   327  	if err != nil {
   328  		return err
   329  	}
   330  	return Chmod(name, fi.Mode()|ModeSticky)
   331  }
   332  
   333  // Chdir changes the current working directory to the named directory.
   334  // If there is an error, it will be of type *PathError.
   335  func Chdir(dir string) error {
   336  	if e := syscall.Chdir(dir); e != nil {
   337  		testlog.Open(dir) // observe likely non-existent directory
   338  		return &PathError{Op: "chdir", Path: dir, Err: e}
   339  	}
   340  	if log := testlog.Logger(); log != nil {
   341  		wd, err := Getwd()
   342  		if err == nil {
   343  			log.Chdir(wd)
   344  		}
   345  	}
   346  	return nil
   347  }
   348  
   349  // Open opens the named file for reading. If successful, methods on
   350  // the returned file can be used for reading; the associated file
   351  // descriptor has mode O_RDONLY.
   352  // If there is an error, it will be of type *PathError.
   353  func Open(name string) (*File, error) {
   354  	return OpenFile(name, O_RDONLY, 0)
   355  }
   356  
   357  // Create creates or truncates the named file. If the file already exists,
   358  // it is truncated. If the file does not exist, it is created with mode 0666
   359  // (before umask). If successful, methods on the returned File can
   360  // be used for I/O; the associated file descriptor has mode O_RDWR.
   361  // If there is an error, it will be of type *PathError.
   362  func Create(name string) (*File, error) {
   363  	return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666)
   364  }
   365  
   366  // OpenFile is the generalized open call; most users will use Open
   367  // or Create instead. It opens the named file with specified flag
   368  // (O_RDONLY etc.). If the file does not exist, and the O_CREATE flag
   369  // is passed, it is created with mode perm (before umask). If successful,
   370  // methods on the returned File can be used for I/O.
   371  // If there is an error, it will be of type *PathError.
   372  func OpenFile(name string, flag int, perm FileMode) (*File, error) {
   373  	testlog.Open(name)
   374  	f, err := openFileNolog(name, flag, perm)
   375  	if err != nil {
   376  		return nil, err
   377  	}
   378  	f.appendMode = flag&O_APPEND != 0
   379  
   380  	return f, nil
   381  }
   382  
   383  // lstat is overridden in tests.
   384  var lstat = Lstat
   385  
   386  // Rename renames (moves) oldpath to newpath.
   387  // If newpath already exists and is not a directory, Rename replaces it.
   388  // OS-specific restrictions may apply when oldpath and newpath are in different directories.
   389  // Even within the same directory, on non-Unix platforms Rename is not an atomic operation.
   390  // If there is an error, it will be of type *LinkError.
   391  func Rename(oldpath, newpath string) error {
   392  	return rename(oldpath, newpath)
   393  }
   394  
   395  // Readlink returns the destination of the named symbolic link.
   396  // If there is an error, it will be of type *PathError.
   397  //
   398  // If the link destination is relative, Readlink returns the relative path
   399  // without resolving it to an absolute one.
   400  func Readlink(name string) (string, error) {
   401  	return readlink(name)
   402  }
   403  
   404  // Many functions in package syscall return a count of -1 instead of 0.
   405  // Using fixCount(call()) instead of call() corrects the count.
   406  func fixCount(n int, err error) (int, error) {
   407  	if n < 0 {
   408  		n = 0
   409  	}
   410  	return n, err
   411  }
   412  
   413  // checkWrapErr is the test hook to enable checking unexpected wrapped errors of poll.ErrFileClosing.
   414  // It is set to true in the export_test.go for tests (including fuzz tests).
   415  var checkWrapErr = false
   416  
   417  // wrapErr wraps an error that occurred during an operation on an open file.
   418  // It passes io.EOF through unchanged, otherwise converts
   419  // poll.ErrFileClosing to ErrClosed and wraps the error in a PathError.
   420  func (f *File) wrapErr(op string, err error) error {
   421  	if err == nil || err == io.EOF {
   422  		return err
   423  	}
   424  	if err == poll.ErrFileClosing {
   425  		err = ErrClosed
   426  	} else if checkWrapErr && errors.Is(err, poll.ErrFileClosing) {
   427  		panic("unexpected error wrapping poll.ErrFileClosing: " + err.Error())
   428  	}
   429  	return &PathError{Op: op, Path: f.name, Err: err}
   430  }
   431  
   432  // TempDir returns the default directory to use for temporary files.
   433  //
   434  // On Unix systems, it returns $TMPDIR if non-empty, else /tmp.
   435  // On Windows, it uses GetTempPath, returning the first non-empty
   436  // value from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory.
   437  // On Plan 9, it returns /tmp.
   438  //
   439  // The directory is neither guaranteed to exist nor have accessible
   440  // permissions.
   441  func TempDir() string {
   442  	return tempDir()
   443  }
   444  
   445  // UserCacheDir returns the default root directory to use for user-specific
   446  // cached data. Users should create their own application-specific subdirectory
   447  // within this one and use that.
   448  //
   449  // On Unix systems, it returns $XDG_CACHE_HOME as specified by
   450  // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html if
   451  // non-empty, else $HOME/.cache.
   452  // On Darwin, it returns $HOME/Library/Caches.
   453  // On Windows, it returns %LocalAppData%.
   454  // On Plan 9, it returns $home/lib/cache.
   455  //
   456  // If the location cannot be determined (for example, $HOME is not defined),
   457  // then it will return an error.
   458  func UserCacheDir() (string, error) {
   459  	var dir string
   460  
   461  	switch runtime.GOOS {
   462  	case "windows":
   463  		dir = Getenv("LocalAppData")
   464  		if dir == "" {
   465  			return "", errors.New("%LocalAppData% is not defined")
   466  		}
   467  
   468  	case "darwin", "ios":
   469  		dir = Getenv("HOME")
   470  		if dir == "" {
   471  			return "", errors.New("$HOME is not defined")
   472  		}
   473  		dir += "/Library/Caches"
   474  
   475  	case "plan9":
   476  		dir = Getenv("home")
   477  		if dir == "" {
   478  			return "", errors.New("$home is not defined")
   479  		}
   480  		dir += "/lib/cache"
   481  
   482  	default: // Unix
   483  		dir = Getenv("XDG_CACHE_HOME")
   484  		if dir == "" {
   485  			dir = Getenv("HOME")
   486  			if dir == "" {
   487  				return "", errors.New("neither $XDG_CACHE_HOME nor $HOME are defined")
   488  			}
   489  			dir += "/.cache"
   490  		}
   491  	}
   492  
   493  	return dir, nil
   494  }
   495  
   496  // UserConfigDir returns the default root directory to use for user-specific
   497  // configuration data. Users should create their own application-specific
   498  // subdirectory within this one and use that.
   499  //
   500  // On Unix systems, it returns $XDG_CONFIG_HOME as specified by
   501  // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html if
   502  // non-empty, else $HOME/.config.
   503  // On Darwin, it returns $HOME/Library/Application Support.
   504  // On Windows, it returns %AppData%.
   505  // On Plan 9, it returns $home/lib.
   506  //
   507  // If the location cannot be determined (for example, $HOME is not defined),
   508  // then it will return an error.
   509  func UserConfigDir() (string, error) {
   510  	var dir string
   511  
   512  	switch runtime.GOOS {
   513  	case "windows":
   514  		dir = Getenv("AppData")
   515  		if dir == "" {
   516  			return "", errors.New("%AppData% is not defined")
   517  		}
   518  
   519  	case "darwin", "ios":
   520  		dir = Getenv("HOME")
   521  		if dir == "" {
   522  			return "", errors.New("$HOME is not defined")
   523  		}
   524  		dir += "/Library/Application Support"
   525  
   526  	case "plan9":
   527  		dir = Getenv("home")
   528  		if dir == "" {
   529  			return "", errors.New("$home is not defined")
   530  		}
   531  		dir += "/lib"
   532  
   533  	default: // Unix
   534  		dir = Getenv("XDG_CONFIG_HOME")
   535  		if dir == "" {
   536  			dir = Getenv("HOME")
   537  			if dir == "" {
   538  				return "", errors.New("neither $XDG_CONFIG_HOME nor $HOME are defined")
   539  			}
   540  			dir += "/.config"
   541  		}
   542  	}
   543  
   544  	return dir, nil
   545  }
   546  
   547  // UserHomeDir returns the current user's home directory.
   548  //
   549  // On Unix, including macOS, it returns the $HOME environment variable.
   550  // On Windows, it returns %USERPROFILE%.
   551  // On Plan 9, it returns the $home environment variable.
   552  //
   553  // If the expected variable is not set in the environment, UserHomeDir
   554  // returns either a platform-specific default value or a non-nil error.
   555  func UserHomeDir() (string, error) {
   556  	env, enverr := "HOME", "$HOME"
   557  	switch runtime.GOOS {
   558  	case "windows":
   559  		env, enverr = "USERPROFILE", "%userprofile%"
   560  	case "plan9":
   561  		env, enverr = "home", "$home"
   562  	}
   563  	if v := Getenv(env); v != "" {
   564  		return v, nil
   565  	}
   566  	// On some geese the home directory is not always defined.
   567  	switch runtime.GOOS {
   568  	case "android":
   569  		return "/sdcard", nil
   570  	case "ios":
   571  		return "/", nil
   572  	}
   573  	return "", errors.New(enverr + " is not defined")
   574  }
   575  
   576  // Chmod changes the mode of the named file to mode.
   577  // If the file is a symbolic link, it changes the mode of the link's target.
   578  // If there is an error, it will be of type *PathError.
   579  //
   580  // A different subset of the mode bits are used, depending on the
   581  // operating system.
   582  //
   583  // On Unix, the mode's permission bits, ModeSetuid, ModeSetgid, and
   584  // ModeSticky are used.
   585  //
   586  // On Windows, only the 0200 bit (owner writable) of mode is used; it
   587  // controls whether the file's read-only attribute is set or cleared.
   588  // The other bits are currently unused. For compatibility with Go 1.12
   589  // and earlier, use a non-zero mode. Use mode 0400 for a read-only
   590  // file and 0600 for a readable+writable file.
   591  //
   592  // On Plan 9, the mode's permission bits, ModeAppend, ModeExclusive,
   593  // and ModeTemporary are used.
   594  func Chmod(name string, mode FileMode) error { return chmod(name, mode) }
   595  
   596  // Chmod changes the mode of the file to mode.
   597  // If there is an error, it will be of type *PathError.
   598  func (f *File) Chmod(mode FileMode) error { return f.chmod(mode) }
   599  
   600  // SetDeadline sets the read and write deadlines for a File.
   601  // It is equivalent to calling both SetReadDeadline and SetWriteDeadline.
   602  //
   603  // Only some kinds of files support setting a deadline. Calls to SetDeadline
   604  // for files that do not support deadlines will return ErrNoDeadline.
   605  // On most systems ordinary files do not support deadlines, but pipes do.
   606  //
   607  // A deadline is an absolute time after which I/O operations fail with an
   608  // error instead of blocking. The deadline applies to all future and pending
   609  // I/O, not just the immediately following call to Read or Write.
   610  // After a deadline has been exceeded, the connection can be refreshed
   611  // by setting a deadline in the future.
   612  //
   613  // If the deadline is exceeded a call to Read or Write or to other I/O
   614  // methods will return an error that wraps ErrDeadlineExceeded.
   615  // This can be tested using errors.Is(err, os.ErrDeadlineExceeded).
   616  // That error implements the Timeout method, and calling the Timeout
   617  // method will return true, but there are other possible errors for which
   618  // the Timeout will return true even if the deadline has not been exceeded.
   619  //
   620  // An idle timeout can be implemented by repeatedly extending
   621  // the deadline after successful Read or Write calls.
   622  //
   623  // A zero value for t means I/O operations will not time out.
   624  func (f *File) SetDeadline(t time.Time) error {
   625  	return f.setDeadline(t)
   626  }
   627  
   628  // SetReadDeadline sets the deadline for future Read calls and any
   629  // currently-blocked Read call.
   630  // A zero value for t means Read will not time out.
   631  // Not all files support setting deadlines; see SetDeadline.
   632  func (f *File) SetReadDeadline(t time.Time) error {
   633  	return f.setReadDeadline(t)
   634  }
   635  
   636  // SetWriteDeadline sets the deadline for any future Write calls and any
   637  // currently-blocked Write call.
   638  // Even if Write times out, it may return n > 0, indicating that
   639  // some of the data was successfully written.
   640  // A zero value for t means Write will not time out.
   641  // Not all files support setting deadlines; see SetDeadline.
   642  func (f *File) SetWriteDeadline(t time.Time) error {
   643  	return f.setWriteDeadline(t)
   644  }
   645  
   646  // SyscallConn returns a raw file.
   647  // This implements the syscall.Conn interface.
   648  func (f *File) SyscallConn() (syscall.RawConn, error) {
   649  	if err := f.checkValid("SyscallConn"); err != nil {
   650  		return nil, err
   651  	}
   652  	return newRawConn(f)
   653  }
   654  
   655  // DirFS returns a file system (an fs.FS) for the tree of files rooted at the directory dir.
   656  //
   657  // Note that DirFS("/prefix") only guarantees that the Open calls it makes to the
   658  // operating system will begin with "/prefix": DirFS("/prefix").Open("file") is the
   659  // same as os.Open("/prefix/file"). So if /prefix/file is a symbolic link pointing outside
   660  // the /prefix tree, then using DirFS does not stop the access any more than using
   661  // os.Open does. Additionally, the root of the fs.FS returned for a relative path,
   662  // DirFS("prefix"), will be affected by later calls to Chdir. DirFS is therefore not
   663  // a general substitute for a chroot-style security mechanism when the directory tree
   664  // contains arbitrary content.
   665  //
   666  // The directory dir must not be "".
   667  //
   668  // The result implements [io/fs.StatFS], [io/fs.ReadFileFS] and
   669  // [io/fs.ReadDirFS].
   670  func DirFS(dir string) fs.FS {
   671  	return dirFS(dir)
   672  }
   673  
   674  type dirFS string
   675  
   676  func (dir dirFS) Open(name string) (fs.File, error) {
   677  	fullname, err := dir.join(name)
   678  	if err != nil {
   679  		return nil, &PathError{Op: "open", Path: name, Err: err}
   680  	}
   681  	f, err := Open(fullname)
   682  	if err != nil {
   683  		// DirFS takes a string appropriate for GOOS,
   684  		// while the name argument here is always slash separated.
   685  		// dir.join will have mixed the two; undo that for
   686  		// error reporting.
   687  		err.(*PathError).Path = name
   688  		return nil, err
   689  	}
   690  	return f, nil
   691  }
   692  
   693  // The ReadFile method calls the [ReadFile] function for the file
   694  // with the given name in the directory. The function provides
   695  // robust handling for small files and special file systems.
   696  // Through this method, dirFS implements [io/fs.ReadFileFS].
   697  func (dir dirFS) ReadFile(name string) ([]byte, error) {
   698  	fullname, err := dir.join(name)
   699  	if err != nil {
   700  		return nil, &PathError{Op: "readfile", Path: name, Err: err}
   701  	}
   702  	b, err := ReadFile(fullname)
   703  	if err != nil {
   704  		if e, ok := err.(*PathError); ok {
   705  			// See comment in dirFS.Open.
   706  			e.Path = name
   707  		}
   708  		return nil, err
   709  	}
   710  	return b, nil
   711  }
   712  
   713  // ReadDir reads the named directory, returning all its directory entries sorted
   714  // by filename. Through this method, dirFS implements [io/fs.ReadDirFS].
   715  func (dir dirFS) ReadDir(name string) ([]DirEntry, error) {
   716  	fullname, err := dir.join(name)
   717  	if err != nil {
   718  		return nil, &PathError{Op: "readdir", Path: name, Err: err}
   719  	}
   720  	entries, err := ReadDir(fullname)
   721  	if err != nil {
   722  		if e, ok := err.(*PathError); ok {
   723  			// See comment in dirFS.Open.
   724  			e.Path = name
   725  		}
   726  		return nil, err
   727  	}
   728  	return entries, nil
   729  }
   730  
   731  func (dir dirFS) Stat(name string) (fs.FileInfo, error) {
   732  	fullname, err := dir.join(name)
   733  	if err != nil {
   734  		return nil, &PathError{Op: "stat", Path: name, Err: err}
   735  	}
   736  	f, err := Stat(fullname)
   737  	if err != nil {
   738  		// See comment in dirFS.Open.
   739  		err.(*PathError).Path = name
   740  		return nil, err
   741  	}
   742  	return f, nil
   743  }
   744  
   745  // join returns the path for name in dir.
   746  func (dir dirFS) join(name string) (string, error) {
   747  	if dir == "" {
   748  		return "", errors.New("os: DirFS with empty root")
   749  	}
   750  	if !fs.ValidPath(name) {
   751  		return "", ErrInvalid
   752  	}
   753  	name, err := safefilepath.FromFS(name)
   754  	if err != nil {
   755  		return "", ErrInvalid
   756  	}
   757  	if IsPathSeparator(dir[len(dir)-1]) {
   758  		return string(dir) + name, nil
   759  	}
   760  	return string(dir) + string(PathSeparator) + name, nil
   761  }
   762  
   763  // ReadFile reads the named file and returns the contents.
   764  // A successful call returns err == nil, not err == EOF.
   765  // Because ReadFile reads the whole file, it does not treat an EOF from Read
   766  // as an error to be reported.
   767  func ReadFile(name string) ([]byte, error) {
   768  	f, err := Open(name)
   769  	if err != nil {
   770  		return nil, err
   771  	}
   772  	defer f.Close()
   773  
   774  	var size int
   775  	if info, err := f.Stat(); err == nil {
   776  		size64 := info.Size()
   777  		if int64(int(size64)) == size64 {
   778  			size = int(size64)
   779  		}
   780  	}
   781  	size++ // one byte for final read at EOF
   782  
   783  	// If a file claims a small size, read at least 512 bytes.
   784  	// In particular, files in Linux's /proc claim size 0 but
   785  	// then do not work right if read in small pieces,
   786  	// so an initial read of 1 byte would not work correctly.
   787  	if size < 512 {
   788  		size = 512
   789  	}
   790  
   791  	data := make([]byte, 0, size)
   792  	for {
   793  		n, err := f.Read(data[len(data):cap(data)])
   794  		data = data[:len(data)+n]
   795  		if err != nil {
   796  			if err == io.EOF {
   797  				err = nil
   798  			}
   799  			return data, err
   800  		}
   801  
   802  		if len(data) >= cap(data) {
   803  			d := append(data[:cap(data)], 0)
   804  			data = d[:len(data)]
   805  		}
   806  	}
   807  }
   808  
   809  // WriteFile writes data to the named file, creating it if necessary.
   810  // If the file does not exist, WriteFile creates it with permissions perm (before umask);
   811  // otherwise WriteFile truncates it before writing, without changing permissions.
   812  // Since WriteFile requires multiple system calls to complete, a failure mid-operation
   813  // can leave the file in a partially written state.
   814  func WriteFile(name string, data []byte, perm FileMode) error {
   815  	f, err := OpenFile(name, O_WRONLY|O_CREATE|O_TRUNC, perm)
   816  	if err != nil {
   817  		return err
   818  	}
   819  	_, err = f.Write(data)
   820  	if err1 := f.Close(); err1 != nil && err == nil {
   821  		err = err1
   822  	}
   823  	return err
   824  }
   825  

View as plain text