Merge from mainline (167278:168000).
[official-gcc/graphite-test-results.git] / libgo / go / io / ioutil / ioutil.go
blobfb3fdcda1e673b6da62ad5de96e5e13cbc9b95b5
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 // Utility functions.
7 package ioutil
9 import (
10 "bytes"
11 "io"
12 "os"
13 "sort"
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) {
18 var buf bytes.Buffer
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)
26 if err != nil {
27 return nil, err
29 defer f.Close()
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.
32 fi, err := f.Stat()
33 var n int64
34 if err == nil && fi.Size < 2e9 { // Don't preallocate a huge buffer, just in case.
35 n = fi.Size
37 // Add a little extra in case Size is zero, and to avoid another allocation after
38 // Read has filled the buffer.
39 n += bytes.MinRead
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)
54 if err != nil {
55 return err
57 n, err := f.Write(data)
58 f.Close()
59 if err == nil && n < len(data) {
60 err = io.ErrShortWrite
62 return err
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)
76 if err != nil {
77 return nil, err
79 list, err := f.Readdir(-1)
80 f.Close()
81 if err != nil {
82 return nil, err
84 fi := make(fileInfoList, len(list))
85 for i := range list {
86 fi[i] = &list[i]
88 sort.Sort(fi)
89 return fi, nil