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//
37package os
38
39import (
40	"io"
41	"syscall"
42)
43
44// Name returns the name of the file as presented to Open.
45func (f *File) Name() string { return f.name }
46
47// Stdin, Stdout, and Stderr are open Files pointing to the standard input,
48// standard output, and standard error file descriptors.
49var (
50	Stdin  = NewFile(uintptr(syscall.Stdin), "/dev/stdin")
51	Stdout = NewFile(uintptr(syscall.Stdout), "/dev/stdout")
52	Stderr = NewFile(uintptr(syscall.Stderr), "/dev/stderr")
53)
54
55// Flags to OpenFile wrapping those of the underlying system. Not all
56// flags may be implemented on a given system.
57const (
58	O_RDONLY int = syscall.O_RDONLY // open the file read-only.
59	O_WRONLY int = syscall.O_WRONLY // open the file write-only.
60	O_RDWR   int = syscall.O_RDWR   // open the file read-write.
61	O_APPEND int = syscall.O_APPEND // append data to the file when writing.
62	O_CREATE int = syscall.O_CREAT  // create a new file if none exists.
63	O_EXCL   int = syscall.O_EXCL   // used with O_CREATE, file must not exist
64	O_SYNC   int = syscall.O_SYNC   // open for synchronous I/O.
65	O_TRUNC  int = syscall.O_TRUNC  // if possible, truncate file when opened.
66)
67
68// Seek whence values.
69const (
70	SEEK_SET int = 0 // seek relative to the origin of the file
71	SEEK_CUR int = 1 // seek relative to the current offset
72	SEEK_END int = 2 // seek relative to the end
73)
74
75// LinkError records an error during a link or symlink or rename
76// system call and the paths that caused it.
77type LinkError struct {
78	Op  string
79	Old string
80	New string
81	Err error
82}
83
84func (e *LinkError) Error() string {
85	return e.Op + " " + e.Old + " " + e.New + ": " + e.Err.Error()
86}
87
88// Read reads up to len(b) bytes from the File.
89// It returns the number of bytes read and an error, if any.
90// EOF is signaled by a zero count with err set to io.EOF.
91func (f *File) Read(b []byte) (n int, err error) {
92	if f == nil {
93		return 0, ErrInvalid
94	}
95	n, e := f.read(b)
96	if n == 0 && len(b) > 0 && e == nil {
97		return 0, io.EOF
98	}
99	if e != nil {
100		err = &PathError{"read", f.name, e}
101	}
102	return n, err
103}
104
105// ReadAt reads len(b) bytes from the File starting at byte offset off.
106// It returns the number of bytes read and the error, if any.
107// ReadAt always returns a non-nil error when n < len(b).
108// At end of file, that error is io.EOF.
109func (f *File) ReadAt(b []byte, off int64) (n int, err error) {
110	if f == nil {
111		return 0, ErrInvalid
112	}
113	for len(b) > 0 {
114		m, e := f.pread(b, off)
115		if m == 0 && e == nil {
116			return n, io.EOF
117		}
118		if e != nil {
119			err = &PathError{"read", f.name, e}
120			break
121		}
122		n += m
123		b = b[m:]
124		off += int64(m)
125	}
126	return
127}
128
129// Write writes len(b) bytes to the File.
130// It returns the number of bytes written and an error, if any.
131// Write returns a non-nil error when n != len(b).
132func (f *File) Write(b []byte) (n int, err error) {
133	if f == nil {
134		return 0, ErrInvalid
135	}
136	n, e := f.write(b)
137	if n < 0 {
138		n = 0
139	}
140	if n != len(b) {
141		err = io.ErrShortWrite
142	}
143
144	epipecheck(f, e)
145
146	if e != nil {
147		err = &PathError{"write", f.name, e}
148	}
149	return n, err
150}
151
152// WriteAt writes len(b) bytes to the File starting at byte offset off.
153// It returns the number of bytes written and an error, if any.
154// WriteAt returns a non-nil error when n != len(b).
155func (f *File) WriteAt(b []byte, off int64) (n int, err error) {
156	if f == nil {
157		return 0, ErrInvalid
158	}
159	for len(b) > 0 {
160		m, e := f.pwrite(b, off)
161		if e != nil {
162			err = &PathError{"write", f.name, e}
163			break
164		}
165		n += m
166		b = b[m:]
167		off += int64(m)
168	}
169	return
170}
171
172// Seek sets the offset for the next Read or Write on file to offset, interpreted
173// according to whence: 0 means relative to the origin of the file, 1 means
174// relative to the current offset, and 2 means relative to the end.
175// It returns the new offset and an error, if any.
176// The behavior of Seek on a file opened with O_APPEND is not specified.
177func (f *File) Seek(offset int64, whence int) (ret int64, err error) {
178	if f == nil {
179		return 0, ErrInvalid
180	}
181	r, e := f.seek(offset, whence)
182	if e == nil && f.dirinfo != nil && r != 0 {
183		e = syscall.EISDIR
184	}
185	if e != nil {
186		return 0, &PathError{"seek", f.name, e}
187	}
188	return r, nil
189}
190
191// WriteString is like Write, but writes the contents of string s rather than
192// a slice of bytes.
193func (f *File) WriteString(s string) (n int, err error) {
194	if f == nil {
195		return 0, ErrInvalid
196	}
197	return f.Write([]byte(s))
198}
199
200// Mkdir creates a new directory with the specified name and permission bits.
201// If there is an error, it will be of type *PathError.
202func Mkdir(name string, perm FileMode) error {
203	e := syscall.Mkdir(name, syscallMode(perm))
204
205	if e != nil {
206		return &PathError{"mkdir", name, e}
207	}
208
209	// mkdir(2) itself won't handle the sticky bit on *BSD and Solaris
210	if !supportsCreateWithStickyBit && perm&ModeSticky != 0 {
211		Chmod(name, perm)
212	}
213
214	return nil
215}
216
217// Chdir changes the current working directory to the named directory.
218// If there is an error, it will be of type *PathError.
219func Chdir(dir string) error {
220	if e := syscall.Chdir(dir); e != nil {
221		return &PathError{"chdir", dir, e}
222	}
223	return nil
224}
225
226// Chdir changes the current working directory to the file,
227// which must be a directory.
228// If there is an error, it will be of type *PathError.
229func (f *File) Chdir() error {
230	if f == nil {
231		return ErrInvalid
232	}
233	if e := syscall.Fchdir(f.fd); e != nil {
234		return &PathError{"chdir", f.name, e}
235	}
236	return nil
237}
238
239// Open opens the named file for reading.  If successful, methods on
240// the returned file can be used for reading; the associated file
241// descriptor has mode O_RDONLY.
242// If there is an error, it will be of type *PathError.
243func Open(name string) (*File, error) {
244	return OpenFile(name, O_RDONLY, 0)
245}
246
247// Create creates the named file with mode 0666 (before umask), truncating
248// it if it already exists. If successful, methods on the returned
249// File can be used for I/O; the associated file descriptor has mode
250// O_RDWR.
251// If there is an error, it will be of type *PathError.
252func Create(name string) (*File, error) {
253	return OpenFile(name, O_RDWR|O_CREATE|O_TRUNC, 0666)
254}
255
256// lstat is overridden in tests.
257var lstat = Lstat
258
259// Rename renames (moves) oldpath to newpath.
260// If newpath already exists, Rename replaces it.
261// OS-specific restrictions may apply when oldpath and newpath are in different directories.
262// If there is an error, it will be of type *LinkError.
263func Rename(oldpath, newpath string) error {
264	return rename(oldpath, newpath)
265}
266
267// Many functions in package syscall return a count of -1 instead of 0.
268// Using fixCount(call()) instead of call() corrects the count.
269func fixCount(n int, err error) (int, error) {
270	if n < 0 {
271		n = 0
272	}
273	return n, err
274}
275