...
Run Format

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

View as plain text