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