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 func ReadAll(r io
.Reader
) ([]byte, os
.Error
) {
19 _
, err
:= io
.Copy(&buf
, r
)
20 return buf
.Bytes(), err
23 // ReadFile reads the file named by filename and returns the contents.
24 func ReadFile(filename
string) ([]byte, os
.Error
) {
25 f
, err
:= os
.Open(filename
, os
.O_RDONLY
, 0)
30 // It's a good but not certain bet that FileInfo will tell us exactly how much to
31 // read, so let's try it but be prepared for the answer to be wrong.
34 if err
== nil && fi
.Size
< 2e9
{ // Don't preallocate a huge buffer, just in case.
37 // Add a little extra in case Size is zero, and to avoid another allocation after
38 // Read has filled the buffer.
40 // Pre-allocate the correct size of buffer, then set its size to zero. The
41 // Buffer will read into the allocated space cheaply. If the size was wrong,
42 // we'll either waste some space off the end or reallocate as needed, but
43 // in the overwhelmingly common case we'll get it just right.
44 buf
:= bytes
.NewBuffer(make([]byte, 0, n
))
45 _
, err
= buf
.ReadFrom(f
)
46 return buf
.Bytes(), err
49 // WriteFile writes data to a file named by filename.
50 // If the file does not exist, WriteFile creates it with permissions perm;
51 // otherwise WriteFile truncates it before writing.
52 func WriteFile(filename
string, data
[]byte, perm
uint32) os
.Error
{
53 f
, err
:= os
.Open(filename
, os
.O_WRONLY|os
.O_CREAT|os
.O_TRUNC
, perm
)
57 n
, err
:= f
.Write(data
)
59 if err
== nil && n
< len(data
) {
60 err
= io
.ErrShortWrite
65 // A dirList implements sort.Interface.
66 type fileInfoList
[]*os
.FileInfo
68 func (f fileInfoList
) Len() int { return len(f
) }
69 func (f fileInfoList
) Less(i
, j
int) bool { return f
[i
].Name
< f
[j
].Name
}
70 func (f fileInfoList
) Swap(i
, j
int) { f
[i
], f
[j
] = f
[j
], f
[i
] }
72 // ReadDir reads the directory named by dirname and returns
73 // a list of sorted directory entries.
74 func ReadDir(dirname
string) ([]*os
.FileInfo
, os
.Error
) {
75 f
, err
:= os
.Open(dirname
, os
.O_RDONLY
, 0)
79 list
, err
:= f
.Readdir(-1)
84 fi
:= make(fileInfoList
, len(list
))