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.
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.
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.
16 // Here is a simple example, opening a file and reading some of it.
18 // file, err := os.Open("file.go") // For read access.
23 // If the open fails, the error string will be self-explanatory, like
25 // open file.go: no such file or directory
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.
30 // data := make([]byte, 100)
31 // count, err := file.Read(data)
35 // fmt.Printf("read %d bytes: %q\n", count, data[:count])
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.
53 // Name returns the name of the file as presented to Open.
54 func (f
*File
) Name() string { return f
.name
}
56 // Stdin, Stdout, and Stderr are open Files pointing to the standard input,
57 // standard output, and standard error file descriptors.
59 // Note that the Go runtime writes to standard error for panics and crashes;
60 // closing Stderr may cause those messages to go elsewhere, perhaps
61 // to a file opened later.
63 Stdin
= NewFile(uintptr(syscall
.Stdin
), "/dev/stdin")
64 Stdout
= NewFile(uintptr(syscall
.Stdout
), "/dev/stdout")
65 Stderr
= NewFile(uintptr(syscall
.Stderr
), "/dev/stderr")
68 // Flags to OpenFile wrapping those of the underlying system. Not all
69 // flags may be implemented on a given system.
71 // Exactly one of O_RDONLY, O_WRONLY, or O_RDWR must be specified.
72 O_RDONLY
int = syscall
.O_RDONLY
// open the file read-only.
73 O_WRONLY
int = syscall
.O_WRONLY
// open the file write-only.
74 O_RDWR
int = syscall
.O_RDWR
// open the file read-write.
75 // The remaining values may be or'ed in to control behavior.
76 O_APPEND
int = syscall
.O_APPEND
// append data to the file when writing.
77 O_CREATE
int = syscall
.O_CREAT
// create a new file if none exists.
78 O_EXCL
int = syscall
.O_EXCL
// used with O_CREATE, file must not exist.
79 O_SYNC
int = syscall
.O_SYNC
// open for synchronous I/O.
80 O_TRUNC
int = syscall
.O_TRUNC
// truncate regular writable file when opened.
83 // Seek whence values.
85 // Deprecated: Use io.SeekStart, io.SeekCurrent, and io.SeekEnd.
87 SEEK_SET
int = 0 // seek relative to the origin of the file
88 SEEK_CUR
int = 1 // seek relative to the current offset
89 SEEK_END
int = 2 // seek relative to the end
92 // LinkError records an error during a link or symlink or rename
93 // system call and the paths that caused it.
94 type LinkError
struct {
101 func (e
*LinkError
) Error() string {
102 return e
.Op
+ " " + e
.Old
+ " " + e
.New
+ ": " + e
.Err
.Error()
105 func (e
*LinkError
) Unwrap() error
{
109 // Read reads up to len(b) bytes from the File.
110 // It returns the number of bytes read and any error encountered.
111 // At end of file, Read returns 0, io.EOF.
112 func (f
*File
) Read(b
[]byte) (n
int, err error
) {
113 if err
:= f
.checkValid("read"); err
!= nil {
117 return n
, f
.wrapErr("read", e
)
120 // ReadAt reads len(b) bytes from the File starting at byte offset off.
121 // It returns the number of bytes read and the error, if any.
122 // ReadAt always returns a non-nil error when n < len(b).
123 // At end of file, that error is io.EOF.
124 func (f
*File
) ReadAt(b
[]byte, off
int64) (n
int, err error
) {
125 if err
:= f
.checkValid("read"); err
!= nil {
130 return 0, &PathError
{"readat", f
.name
, errors
.New("negative offset")}
134 m
, e
:= f
.pread(b
, off
)
136 err
= f
.wrapErr("read", e
)
146 // Write writes len(b) bytes to the File.
147 // It returns the number of bytes written and an error, if any.
148 // Write returns a non-nil error when n != len(b).
149 func (f
*File
) Write(b
[]byte) (n
int, err error
) {
150 if err
:= f
.checkValid("write"); err
!= nil {
158 err
= io
.ErrShortWrite
164 err
= f
.wrapErr("write", e
)
170 var errWriteAtInAppendMode
= errors
.New("os: invalid use of WriteAt on file opened with O_APPEND")
172 // WriteAt writes len(b) bytes to the File starting at byte offset off.
173 // It returns the number of bytes written and an error, if any.
174 // WriteAt returns a non-nil error when n != len(b).
176 // If file was opened with the O_APPEND flag, WriteAt returns an error.
177 func (f
*File
) WriteAt(b
[]byte, off
int64) (n
int, err error
) {
178 if err
:= f
.checkValid("write"); err
!= nil {
182 return 0, errWriteAtInAppendMode
186 return 0, &PathError
{"writeat", f
.name
, errors
.New("negative offset")}
190 m
, e
:= f
.pwrite(b
, off
)
192 err
= f
.wrapErr("write", e
)
202 // Seek sets the offset for the next Read or Write on file to offset, interpreted
203 // according to whence: 0 means relative to the origin of the file, 1 means
204 // relative to the current offset, and 2 means relative to the end.
205 // It returns the new offset and an error, if any.
206 // The behavior of Seek on a file opened with O_APPEND is not specified.
207 func (f
*File
) Seek(offset
int64, whence
int) (ret
int64, err error
) {
208 if err
:= f
.checkValid("seek"); err
!= nil {
211 r
, e
:= f
.seek(offset
, whence
)
212 if e
== nil && f
.dirinfo
!= nil && r
!= 0 {
216 return 0, f
.wrapErr("seek", e
)
221 // WriteString is like Write, but writes the contents of string s rather than
223 func (f
*File
) WriteString(s
string) (n
int, err error
) {
224 return f
.Write([]byte(s
))
227 // Mkdir creates a new directory with the specified name and permission
228 // bits (before umask).
229 // If there is an error, it will be of type *PathError.
230 func Mkdir(name
string, perm FileMode
) error
{
231 if runtime
.GOOS
== "windows" && isWindowsNulName(name
) {
232 return &PathError
{"mkdir", name
, syscall
.ENOTDIR
}
234 e
:= syscall
.Mkdir(fixLongPath(name
), syscallMode(perm
))
237 return &PathError
{"mkdir", name
, e
}
240 // mkdir(2) itself won't handle the sticky bit on *BSD and Solaris
241 if !supportsCreateWithStickyBit
&& perm
&ModeSticky
!= 0 {
242 e
= setStickyBit(name
)
253 // setStickyBit adds ModeSticky to the permission bits of path, non atomic.
254 func setStickyBit(name
string) error
{
255 fi
, err
:= Stat(name
)
259 return Chmod(name
, fi
.Mode()|ModeSticky
)
262 // Chdir changes the current working directory to the named directory.
263 // If there is an error, it will be of type *PathError.
264 func Chdir(dir
string) error
{
265 if e
:= syscall
.Chdir(dir
); e
!= nil {
266 testlog
.Open(dir
) // observe likely non-existent directory
267 return &PathError
{"chdir", dir
, e
}
269 if log
:= testlog
.Logger(); log
!= nil {
278 // Open opens the named file for reading. If successful, methods on
279 // the returned file can be used for reading; the associated file
280 // descriptor has mode O_RDONLY.
281 // If there is an error, it will be of type *PathError.
282 func Open(name
string) (*File
, error
) {
283 return OpenFile(name
, O_RDONLY
, 0)
286 // Create creates or truncates the named file. If the file already exists,
287 // it is truncated. If the file does not exist, it is created with mode 0666
288 // (before umask). If successful, methods on the returned File can
289 // be used for I/O; the associated file descriptor has mode O_RDWR.
290 // If there is an error, it will be of type *PathError.
291 func Create(name
string) (*File
, error
) {
292 return OpenFile(name
, O_RDWR|O_CREATE|O_TRUNC
, 0666)
295 // OpenFile is the generalized open call; most users will use Open
296 // or Create instead. It opens the named file with specified flag
297 // (O_RDONLY etc.). If the file does not exist, and the O_CREATE flag
298 // is passed, it is created with mode perm (before umask). If successful,
299 // methods on the returned File can be used for I/O.
300 // If there is an error, it will be of type *PathError.
301 func OpenFile(name
string, flag
int, perm FileMode
) (*File
, error
) {
303 f
, err
:= openFileNolog(name
, flag
, perm
)
307 f
.appendMode
= flag
&O_APPEND
!= 0
312 // lstat is overridden in tests.
315 // Rename renames (moves) oldpath to newpath.
316 // If newpath already exists and is not a directory, Rename replaces it.
317 // OS-specific restrictions may apply when oldpath and newpath are in different directories.
318 // If there is an error, it will be of type *LinkError.
319 func Rename(oldpath
, newpath
string) error
{
320 return rename(oldpath
, newpath
)
323 // Many functions in package syscall return a count of -1 instead of 0.
324 // Using fixCount(call()) instead of call() corrects the count.
325 func fixCount(n
int, err error
) (int, error
) {
332 // wrapErr wraps an error that occurred during an operation on an open file.
333 // It passes io.EOF through unchanged, otherwise converts
334 // poll.ErrFileClosing to ErrClosed and wraps the error in a PathError.
335 func (f
*File
) wrapErr(op
string, err error
) error
{
336 if err
== nil || err
== io
.EOF
{
339 if err
== poll
.ErrFileClosing
{
342 return &PathError
{op
, f
.name
, err
}
345 // TempDir returns the default directory to use for temporary files.
347 // On Unix systems, it returns $TMPDIR if non-empty, else /tmp.
348 // On Windows, it uses GetTempPath, returning the first non-empty
349 // value from %TMP%, %TEMP%, %USERPROFILE%, or the Windows directory.
350 // On Plan 9, it returns /tmp.
352 // The directory is neither guaranteed to exist nor have accessible
354 func TempDir() string {
358 // UserCacheDir returns the default root directory to use for user-specific
359 // cached data. Users should create their own application-specific subdirectory
360 // within this one and use that.
362 // On Unix systems, it returns $XDG_CACHE_HOME as specified by
363 // https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html if
364 // non-empty, else $HOME/.cache.
365 // On Darwin, it returns $HOME/Library/Caches.
366 // On Windows, it returns %LocalAppData%.
367 // On Plan 9, it returns $home/lib/cache.
369 // If the location cannot be determined (for example, $HOME is not defined),
370 // then it will return an error.
371 func UserCacheDir() (string, error
) {
374 switch runtime
.GOOS
{
376 dir
= Getenv("LocalAppData")
378 return "", errors
.New("%LocalAppData% is not defined")
384 return "", errors
.New("$HOME is not defined")
386 dir
+= "/Library/Caches"
391 return "", errors
.New("$home is not defined")
396 dir
= Getenv("XDG_CACHE_HOME")
400 return "", errors
.New("neither $XDG_CACHE_HOME nor $HOME are defined")
409 // UserConfigDir returns the default root directory to use for user-specific
410 // configuration data. Users should create their own application-specific
411 // subdirectory within this one and use that.
413 // On Unix systems, it returns $XDG_CONFIG_HOME as specified by
414 // https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html if
415 // non-empty, else $HOME/.config.
416 // On Darwin, it returns $HOME/Library/Application Support.
417 // On Windows, it returns %AppData%.
418 // On Plan 9, it returns $home/lib.
420 // If the location cannot be determined (for example, $HOME is not defined),
421 // then it will return an error.
422 func UserConfigDir() (string, error
) {
425 switch runtime
.GOOS
{
427 dir
= Getenv("AppData")
429 return "", errors
.New("%AppData% is not defined")
435 return "", errors
.New("$HOME is not defined")
437 dir
+= "/Library/Application Support"
442 return "", errors
.New("$home is not defined")
447 dir
= Getenv("XDG_CONFIG_HOME")
451 return "", errors
.New("neither $XDG_CONFIG_HOME nor $HOME are defined")
460 // UserHomeDir returns the current user's home directory.
462 // On Unix, including macOS, it returns the $HOME environment variable.
463 // On Windows, it returns %USERPROFILE%.
464 // On Plan 9, it returns the $home environment variable.
465 func UserHomeDir() (string, error
) {
466 env
, enverr
:= "HOME", "$HOME"
467 switch runtime
.GOOS
{
469 env
, enverr
= "USERPROFILE", "%userprofile%"
471 env
, enverr
= "home", "$home"
473 if v
:= Getenv(env
); v
!= "" {
476 // On some geese the home directory is not always defined.
477 switch runtime
.GOOS
{
479 return "/sdcard", nil
481 if runtime
.GOARCH
== "arm" || runtime
.GOARCH
== "arm64" {
485 return "", errors
.New(enverr
+ " is not defined")
488 // Chmod changes the mode of the named file to mode.
489 // If the file is a symbolic link, it changes the mode of the link's target.
490 // If there is an error, it will be of type *PathError.
492 // A different subset of the mode bits are used, depending on the
495 // On Unix, the mode's permission bits, ModeSetuid, ModeSetgid, and
496 // ModeSticky are used.
498 // On Windows, only the 0200 bit (owner writable) of mode is used; it
499 // controls whether the file's read-only attribute is set or cleared.
500 // The other bits are currently unused. For compatibility with Go 1.12
501 // and earlier, use a non-zero mode. Use mode 0400 for a read-only
502 // file and 0600 for a readable+writable file.
504 // On Plan 9, the mode's permission bits, ModeAppend, ModeExclusive,
505 // and ModeTemporary are used.
506 func Chmod(name
string, mode FileMode
) error
{ return chmod(name
, mode
) }
508 // Chmod changes the mode of the file to mode.
509 // If there is an error, it will be of type *PathError.
510 func (f
*File
) Chmod(mode FileMode
) error
{ return f
.chmod(mode
) }
512 // SetDeadline sets the read and write deadlines for a File.
513 // It is equivalent to calling both SetReadDeadline and SetWriteDeadline.
515 // Only some kinds of files support setting a deadline. Calls to SetDeadline
516 // for files that do not support deadlines will return ErrNoDeadline.
517 // On most systems ordinary files do not support deadlines, but pipes do.
519 // A deadline is an absolute time after which I/O operations fail with an
520 // error instead of blocking. The deadline applies to all future and pending
521 // I/O, not just the immediately following call to Read or Write.
522 // After a deadline has been exceeded, the connection can be refreshed
523 // by setting a deadline in the future.
525 // An error returned after a timeout fails will implement the
526 // Timeout method, and calling the Timeout method will return true.
527 // The PathError and SyscallError types implement the Timeout method.
528 // In general, call IsTimeout to test whether an error indicates a timeout.
530 // An idle timeout can be implemented by repeatedly extending
531 // the deadline after successful Read or Write calls.
533 // A zero value for t means I/O operations will not time out.
534 func (f
*File
) SetDeadline(t time
.Time
) error
{
535 return f
.setDeadline(t
)
538 // SetReadDeadline sets the deadline for future Read calls and any
539 // currently-blocked Read call.
540 // A zero value for t means Read will not time out.
541 // Not all files support setting deadlines; see SetDeadline.
542 func (f
*File
) SetReadDeadline(t time
.Time
) error
{
543 return f
.setReadDeadline(t
)
546 // SetWriteDeadline sets the deadline for any future Write calls and any
547 // currently-blocked Write call.
548 // Even if Write times out, it may return n > 0, indicating that
549 // some of the data was successfully written.
550 // A zero value for t means Write will not time out.
551 // Not all files support setting deadlines; see SetDeadline.
552 func (f
*File
) SetWriteDeadline(t time
.Time
) error
{
553 return f
.setWriteDeadline(t
)
556 // SyscallConn returns a raw file.
557 // This implements the syscall.Conn interface.
558 func (f
*File
) SyscallConn() (syscall
.RawConn
, error
) {
559 if err
:= f
.checkValid("SyscallConn"); err
!= nil {
565 // isWindowsNulName reports whether name is os.DevNull ('NUL') on Windows.
566 // True is returned if name is 'NUL' whatever the case.
567 func isWindowsNulName(name
string) bool {
571 if name
[0] != 'n' && name
[0] != 'N' {
574 if name
[1] != 'u' && name
[1] != 'U' {
577 if name
[2] != 'l' && name
[2] != 'L' {