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