...
Run Format

Source file src/io/ioutil/example_test.go

Documentation: io/ioutil

     1  // Copyright 2015 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_test
     6  
     7  import (
     8  	"fmt"
     9  	"io/ioutil"
    10  	"log"
    11  	"os"
    12  	"path/filepath"
    13  	"strings"
    14  )
    15  
    16  func ExampleReadAll() {
    17  	r := strings.NewReader("Go is a general-purpose language designed with systems programming in mind.")
    18  
    19  	b, err := ioutil.ReadAll(r)
    20  	if err != nil {
    21  		log.Fatal(err)
    22  	}
    23  
    24  	fmt.Printf("%s", b)
    25  
    26  	// Output:
    27  	// Go is a general-purpose language designed with systems programming in mind.
    28  }
    29  
    30  func ExampleReadDir() {
    31  	files, err := ioutil.ReadDir(".")
    32  	if err != nil {
    33  		log.Fatal(err)
    34  	}
    35  
    36  	for _, file := range files {
    37  		fmt.Println(file.Name())
    38  	}
    39  }
    40  
    41  func ExampleTempDir() {
    42  	content := []byte("temporary file's content")
    43  	dir, err := ioutil.TempDir("", "example")
    44  	if err != nil {
    45  		log.Fatal(err)
    46  	}
    47  
    48  	defer os.RemoveAll(dir) // clean up
    49  
    50  	tmpfn := filepath.Join(dir, "tmpfile")
    51  	if err := ioutil.WriteFile(tmpfn, content, 0666); err != nil {
    52  		log.Fatal(err)
    53  	}
    54  }
    55  
    56  func ExampleTempFile() {
    57  	content := []byte("temporary file's content")
    58  	tmpfile, err := ioutil.TempFile("", "example")
    59  	if err != nil {
    60  		log.Fatal(err)
    61  	}
    62  
    63  	defer os.Remove(tmpfile.Name()) // clean up
    64  
    65  	if _, err := tmpfile.Write(content); err != nil {
    66  		log.Fatal(err)
    67  	}
    68  	if err := tmpfile.Close(); err != nil {
    69  		log.Fatal(err)
    70  	}
    71  }
    72  
    73  func ExampleReadFile() {
    74  	content, err := ioutil.ReadFile("testdata/hello")
    75  	if err != nil {
    76  		log.Fatal(err)
    77  	}
    78  
    79  	fmt.Printf("File contents: %s", content)
    80  
    81  	// Output:
    82  	// File contents: Hello, Gophers!
    83  }
    84  

View as plain text