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