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.
16 // readAll reads from r until an error or EOF and returns the data it read
17 // from the internal buffer allocated with a specified capacity.
18 func readAll(r io.Reader, capacity int64) ([]byte, os.Error) {
19 buf := bytes.NewBuffer(make([]byte, 0, capacity))
20 _, err := buf.ReadFrom(r)
21 return buf.Bytes(), err
24 // ReadAll reads from r until an error or EOF and returns the data it read.
25 func ReadAll(r io.Reader) ([]byte, os.Error) {
26 return readAll(r, bytes.MinRead)
29 // ReadFile reads the file named by filename and returns the contents.
30 func ReadFile(filename string) ([]byte, os.Error) {
31 f, err := os.Open(filename)
36 // It's a good but not certain bet that FileInfo will tell us exactly how much to
37 // read, so let's try it but be prepared for the answer to be wrong.
40 if err == nil && fi.Size < 2e9 { // Don't preallocate a huge buffer, just in case.
43 // As initial capacity for readAll, use n + a little extra in case Size is zero,
44 // and to avoid another allocation after Read has filled the buffer. The readAll
45 // call will read into its allocated internal buffer cheaply. If the size was
46 // wrong, we'll either waste some space off the end or reallocate as needed, but
47 // in the overwhelmingly common case we'll get it just right.
48 return readAll(f, n+bytes.MinRead)
51 // WriteFile writes data to a file named by filename.
52 // If the file does not exist, WriteFile creates it with permissions perm;
53 // otherwise WriteFile truncates it before writing.
54 func WriteFile(filename string, data []byte, perm uint32) os.Error {
55 f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
59 n, err := f.Write(data)
61 if err == nil && n < len(data) {
62 err = io.ErrShortWrite
67 // A dirList implements sort.Interface.
68 type fileInfoList []*os.FileInfo
70 func (f fileInfoList) Len() int { return len(f) }
71 func (f fileInfoList) Less(i, j int) bool { return f[i].Name < f[j].Name }
72 func (f fileInfoList) Swap(i, j int) { f[i], f[j] = f[j], f[i] }
74 // ReadDir reads the directory named by dirname and returns
75 // a list of sorted directory entries.
76 func ReadDir(dirname string) ([]*os.FileInfo, os.Error) {
77 f, err := os.Open(dirname)
81 list, err := f.Readdir(-1)
86 fi := make(fileInfoList, len(list))
94 type nopCloser struct {
98 func (nopCloser) Close() os.Error { return nil }
100 // NopCloser returns a ReadCloser with a no-op Close method wrapping
101 // the provided Reader r.
102 func NopCloser(r io.Reader) io.ReadCloser {