The Go Programming Language

Source file src/pkg/io/ioutil/ioutil.go

     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 ioutil implements some I/O utility functions.
     6	package ioutil
     7	
     8	import (
     9		"bytes"
    10		"io"
    11		"os"
    12		"sort"
    13	)
    14	
    15	// readAll reads from r until an error or EOF and returns the data it read
    16	// from the internal buffer allocated with a specified capacity.
    17	func readAll(r io.Reader, capacity int64) ([]byte, os.Error) {
    18		buf := bytes.NewBuffer(make([]byte, 0, capacity))
    19		_, err := buf.ReadFrom(r)
    20		return buf.Bytes(), err
    21	}
    22	
    23	// ReadAll reads from r until an error or EOF and returns the data it read.
    24	func ReadAll(r io.Reader) ([]byte, os.Error) {
    25		return readAll(r, bytes.MinRead)
    26	}
    27	
    28	// ReadFile reads the file named by filename and returns the contents.
    29	func ReadFile(filename string) ([]byte, os.Error) {
    30		f, err := os.Open(filename)
    31		if err != nil {
    32			return nil, err
    33		}
    34		defer f.Close()
    35		// It's a good but not certain bet that FileInfo will tell us exactly how much to
    36		// read, so let's try it but be prepared for the answer to be wrong.
    37		fi, err := f.Stat()
    38		var n int64
    39		if err == nil && fi.Size < 2e9 { // Don't preallocate a huge buffer, just in case.
    40			n = fi.Size
    41		}
    42		// As initial capacity for readAll, use n + a little extra in case Size is zero,
    43		// and to avoid another allocation after Read has filled the buffer.  The readAll
    44		// call will read into its allocated internal buffer cheaply.  If the size was
    45		// wrong, we'll either waste some space off the end or reallocate as needed, but
    46		// in the overwhelmingly common case we'll get it just right.
    47		return readAll(f, n+bytes.MinRead)
    48	}
    49	
    50	// WriteFile writes data to a file named by filename.
    51	// If the file does not exist, WriteFile creates it with permissions perm;
    52	// otherwise WriteFile truncates it before writing.
    53	func WriteFile(filename string, data []byte, perm uint32) os.Error {
    54		f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
    55		if err != nil {
    56			return err
    57		}
    58		n, err := f.Write(data)
    59		f.Close()
    60		if err == nil && n < len(data) {
    61			err = io.ErrShortWrite
    62		}
    63		return err
    64	}
    65	
    66	// A fileInfoList implements sort.Interface.
    67	type fileInfoList []*os.FileInfo
    68	
    69	func (f fileInfoList) Len() int           { return len(f) }
    70	func (f fileInfoList) Less(i, j int) bool { return f[i].Name < f[j].Name }
    71	func (f fileInfoList) Swap(i, j int)      { f[i], f[j] = f[j], f[i] }
    72	
    73	// ReadDir reads the directory named by dirname and returns
    74	// a list of sorted directory entries.
    75	func ReadDir(dirname string) ([]*os.FileInfo, os.Error) {
    76		f, err := os.Open(dirname)
    77		if err != nil {
    78			return nil, err
    79		}
    80		list, err := f.Readdir(-1)
    81		f.Close()
    82		if err != nil {
    83			return nil, err
    84		}
    85		fi := make(fileInfoList, len(list))
    86		for i := range list {
    87			fi[i] = &list[i]
    88		}
    89		sort.Sort(fi)
    90		return fi, nil
    91	}
    92	
    93	type nopCloser struct {
    94		io.Reader
    95	}
    96	
    97	func (nopCloser) Close() os.Error { return nil }
    98	
    99	// NopCloser returns a ReadCloser with a no-op Close method wrapping
   100	// the provided Reader r.
   101	func NopCloser(r io.Reader) io.ReadCloser {
   102		return nopCloser{r}
   103	}
   104	
   105	type devNull int
   106	
   107	func (devNull) Write(p []byte) (int, os.Error) {
   108		return len(p), nil
   109	}
   110	
   111	var blackHole = make([]byte, 8192)
   112	
   113	func (devNull) ReadFrom(r io.Reader) (n int64, err os.Error) {
   114		readSize := 0
   115		for {
   116			readSize, err = r.Read(blackHole)
   117			n += int64(readSize)
   118			if err != nil {
   119				if err == os.EOF {
   120					return n, nil
   121				}
   122				return
   123			}
   124		}
   125		panic("unreachable")
   126	}
   127	
   128	// Discard is an io.Writer on which all Write calls succeed
   129	// without doing anything.
   130	var Discard io.Writer = devNull(0)

release.r60.3. Except as noted, this content is licensed under a Creative Commons Attribution 3.0 License.