github.com/karrick/go@v0.0.0-20170817181416-d5b0ec858b37/src/os/file.go (about)

     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  package os
    38  
    39  import (
    40  	"errors"
    41  	"internal/poll"
    42  	"io"
    43  	"syscall"
    44  )
    45  
    46  // Name returns the name of the file as presented to Open.
    47  func (f *File) Name() string { return f.name }
    48  
    49  // Stdin, Stdout, and Stderr are open Files pointing to the standard input,
    50  // standard output, and standard error file descriptors.
    51  //
    52  // Note that the Go runtime writes to standard error for panics and crashes;
    53  // closing Stderr may cause those messages to go elsewhere, perhaps
    54  // to a file opened later.
    55  var (
    56  	Stdin  = NewFile(uintptr(syscall.Stdin), "/dev/stdin")
    57  	Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout")
    58  	Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr")
    59  )
    60  
    61  // Flags to OpenFile wrapping those of the underlying system. Not all
    62  // flags may be implemented on a given system.
    63  const (
    64  	O_RDONLY int = syscall.O_RDONLY // open the file read-only.
    65  	O_WRONLY int = syscall.O_WRONLY // open the file write-only.
    66  	O_RDWR   int = syscall.O_RDWR   // open the file read-write.
    67  	O_APPEND int = syscall.O_APPEND // append data to the file when writing.
    68  	O_CREATE int = syscall.O_CREAT  // create a new file if none exists.
    69  	O_EXCL   int = syscall.O_EXCL   // used with O_CREATE, file must not exist
    70  	O_SYNC   int = syscall.O_SYNC   // open for synchronous I/O.
    71  	O_TRUNC  int = syscall.O_TRUNC  // if possible, truncate file when opened.
    72  )
    73  
    74  // Seek whence values.
    75  //
    76  // Deprecated: Use io.SeekStart, io.SeekCurrent, and io.SeekEnd.
    77  const (
    78  	SEEK_SET int = 0 // seek relative to the origin of the file
    79  	SEEK_CUR int = 1 // seek relative to the current offset
    80  	SEEK_END int = 2 // seek relative to the end
    81  )
    82  
    83  // LinkError records an error during a link or symlink or rename
    84  // system call and the paths that caused it.
    85  type LinkError struct {
    86  	Op  string
    87  	Old string
    88  	New string
    89  	Err error
    90  }
    91  
    92  func (e *LinkError) Error() string {
    93  	return e.Op + " " + e.Old + " " + e.New + ": " + e.Err.Error()
    94  }
    95  
    96  // Read reads up to len(b) bytes from the File.
    97  // It returns the number of bytes read and any error encountered.
    98  // At end of file, Read returns 0, io.EOF.
    99  func (f *File) Read(b []byte) (n int, err error) {
   100  	if err := f.checkValid("read"); err != nil {
   101  		return 0, err
   102  	}
   103  	n, e := f.read(b)
   104  	return n, f.wrapErr("read", e)
   105  }
   106  
   107  // ReadAt reads len(b) bytes from the File starting at byte offset off.
   108  // It returns the number of bytes read and the error, if any.
   109  // ReadAt always returns a non-nil error when n < len(b).
   110  // At end of file, that error is io.EOF.
   111  func (f *File) ReadAt(b []byte, off int64) (n int, err error) {
   112  	if err := f.checkValid("read"); err != nil {
   113  		return 0, err
   114  	}
   115  
   116  	if off < 0 {
   117  		return 0, &PathError{"readat", f.name, errors.New("negative offset")}
   118  	}
   119  
   120  	for len(b) > 0 {
   121  		m, e := f.pread(b, off)
   122  		if e != nil {
   123  			err = f.wrapErr("read", e)
   124  			break
   125  		}
   126  		n += m
   127  		b = b[m:]
   128  		off += int64(m)
   129  	}
   130  	return
   131  }
   132  
   133  // Write writes len(b) bytes to the File.
   134  // It returns the number of bytes written and an error, if any.
   135  // Write returns a non-nil error when n != len(b).
   136  func (f *File) Write(b []byte) (n int, err error) {
   137  	if err := f.checkValid("write"); err != nil {
   138  		return 0, err
   139  	}
   140  	n, e := f.write(b)
   141  	if n < 0 {
   142  		n = 0
   143  	}
   144  	if n != len(b) {
   145  		err = io.ErrShortWrite
   146  	}
   147  
   148  	epipecheck(f, e)
   149  
   150  	if e != nil {
   151  		err = f.wrapErr("write", e)
   152  	}
   153  
   154  	return n, err
   155  }
   156  
   157  // WriteAt writes len(b) bytes to the File starting at byte offset off.
   158  // It returns the number of bytes written and an error, if any.
   159  // WriteAt returns a non-nil error when n != len(b).
   160  func (f *File) WriteAt(b []byte, off int64) (n int, err error) {
   161  	if err := f.checkValid("write"); err != nil {
   162  		return 0, err
   163  	}
   164  
   165  	if off < 0 {
   166  		return 0, &PathError{"writeat", f.name, errors.New("negative offset")}
   167  	}
   168  
   169  	for len(b) > 0 {
   170  		m, e := f.pwrite(b, off)
   171  		if e != nil {
   172  			err = f.wrapErr("write", e)
   173  			break
   174  		}
   175  		n += m
   176  		b = b[m:]
   177  		off += int64(m)
   178  	}
   179  	return
   180  }
   181  
   182  // Seek sets the offset for the next Read or Write on file to offset, interpreted
   183  // according to whence: 0 means relative to the origin of the file, 1 means
   184  // relative to the current offset, and 2 means relative to the end.
   185  // It returns the new offset and an error, if any.
   186  // The behavior of Seek on a file opened with O_APPEND is not specified.
   187  func (f *File) Seek(offset int64, whence int) (ret int64, err error) {
   188  	if err := f.checkValid("seek"); err != nil {
   189  		return 0, err
   190  	}
   191  	r, e := f.seek(offset, whence)
   192  	if e == nil && f.dirinfo != nil && r != 0 {
   193  		e = syscall.EISDIR
   194  	}
   195  	if e != nil {
   196  		return 0, f.wrapErr("seek", e)
   197  	}
   198  	return r, nil
   199  }
   200  
   201  // WriteString is like Write, but writes the contents of string s rather than
   202  // a slice of bytes.
   203  func (f *File) WriteString(s string) (n int, err error) {
   204  	return f.Write([]byte(s))
   205  }
   206  
   207  // Mkdir creates a new directory with the specified name and permission bits.
   208  // If there is an error, it will be of type *PathError.
   209  func Mkdir(name string, perm FileMode) error {
   210  	e := syscall.Mkdir(fixLongPath(name), syscallMode(perm))
   211  
   212  	if e != nil {
   213  		return &PathError{"mkdir", name, e}
   214  	}
   215  
   216  	// mkdir(2) itself won't handle the sticky bit on *BSD and Solaris
   217  	if !supportsCreateWithStickyBit && perm&ModeSticky != 0 {
   218  		Chmod(name, perm)
   219  	}
   220  
   221  	return nil
   222  }
   223  
   224  // Chdir changes the current working directory to the named directory.
   225  // If there is an error, it will be of type *PathError.
   226  func Chdir(dir string) error {
   227  	if e := syscall.Chdir(dir); e != nil {
   228  		return &PathError{"chdir", dir, e}
   229  	}
   230  	return nil
   231  }
   232  
   233  // Open opens the named file for reading. If successful, methods on
   234  // the returned file can be used for reading; the associated file
   235  // descriptor has mode O_RDONLY.
   236  // If there is an error, it will be of type *PathError.
   237  func Open(name string) (*File, error) {
   238  	return OpenFile(name, O_RDONLY, 0)
   239  }
   240  
   241  // Create creates the named file with mode 0666 (before umask), truncating
   242  // it if it already exists. If successful, methods on the returned
   243  // File can be used for I/O; the associated file descriptor has mode
   244  // O_RDWR.
   245  // If there is an error, it will be of type *PathError.
   246  func Create(name string) (*File, error) {
   247  	return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666)
   248  }
   249  
   250  // lstat is overridden in tests.
   251  var lstat = Lstat
   252  
   253  // Rename renames (moves) oldpath to newpath.
   254  // If newpath already exists and is not a directory, Rename replaces it.
   255  // OS-specific restrictions may apply when oldpath and newpath are in different directories.
   256  // If there is an error, it will be of type *LinkError.
   257  func Rename(oldpath, newpath string) error {
   258  	return rename(oldpath, newpath)
   259  }
   260  
   261  // Many functions in package syscall return a count of -1 instead of 0.
   262  // Using fixCount(call()) instead of call() corrects the count.
   263  func fixCount(n int, err error) (int, error) {
   264  	if n < 0 {
   265  		n = 0
   266  	}
   267  	return n, err
   268  }
   269  
   270  // wrapErr wraps an error that occurred during an operation on an open file.
   271  // It passes io.EOF through unchanged, otherwise converts
   272  // poll.ErrFileClosing to ErrClosed and wraps the error in a PathError.
   273  func (f *File) wrapErr(op string, err error) error {
   274  	if err == nil || err == io.EOF {
   275  		return err
   276  	}
   277  	if err == poll.ErrFileClosing {
   278  		err = ErrClosed
   279  	}
   280  	return &PathError{op, f.name, err}
   281  }
   282  
   283  // TempDir returns the default directory to use for temporary files.
   284  //
   285  // On Unix systems, it returns $TMPDIR if non-empty, else /tmp.
   286  // On Windows, it uses GetTempPath, returning the first non-empty
   287  // value from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory.
   288  // On Plan 9, it returns /tmp.
   289  //
   290  // The directory is neither guaranteed to exist nor have accessible
   291  // permissions.
   292  func TempDir() string {
   293  	return tempDir()
   294  }
   295  
   296  // Chmod changes the mode of the named file to mode.
   297  // If the file is a symbolic link, it changes the mode of the link's target.
   298  // If there is an error, it will be of type *PathError.
   299  //
   300  // A different subset of the mode bits are used, depending on the
   301  // operating system.
   302  //
   303  // On Unix, the mode's permission bits, ModeSetuid, ModeSetgid, and
   304  // ModeSticky are used.
   305  //
   306  // On Windows, the mode must be non-zero but otherwise only the 0200
   307  // bit (owner writable) of mode is used; it controls whether the
   308  // file's read-only attribute is set or cleared. attribute. The other
   309  // bits are currently unused. Use mode 0400 for a read-only file and
   310  // 0600 for a readable+writable file.
   311  //
   312  // On Plan 9, the mode's permission bits, ModeAppend, ModeExclusive,
   313  // and ModeTemporary are used.
   314  func Chmod(name string, mode FileMode) error { return chmod(name, mode) }
   315  
   316  // Chmod changes the mode of the file to mode.
   317  // If there is an error, it will be of type *PathError.
   318  func (f *File) Chmod(mode FileMode) error { return f.chmod(mode) }