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

View as plain text