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