libgo: update to go1.9
[official-gcc.git] / libgo / go / os / example_test.go
blob5749194871b795f6e49cb8b64d799abbc1e2e1b2
1 // Copyright 2016 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 package os_test
7 import (
8 "fmt"
9 "log"
10 "os"
11 "time"
14 func ExampleOpenFile() {
15 f, err := os.OpenFile("notes.txt", os.O_RDWR|os.O_CREATE, 0755)
16 if err != nil {
17 log.Fatal(err)
19 if err := f.Close(); err != nil {
20 log.Fatal(err)
24 func ExampleOpenFile_append() {
25 // If the file doesn't exist, create it, or append to the file
26 f, err := os.OpenFile("access.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
27 if err != nil {
28 log.Fatal(err)
30 if _, err := f.Write([]byte("appended some data\n")); err != nil {
31 log.Fatal(err)
33 if err := f.Close(); err != nil {
34 log.Fatal(err)
38 func ExampleChmod() {
39 if err := os.Chmod("some-filename", 0644); err != nil {
40 log.Fatal(err)
44 func ExampleChtimes() {
45 mtime := time.Date(2006, time.February, 1, 3, 4, 5, 0, time.UTC)
46 atime := time.Date(2007, time.March, 2, 4, 5, 6, 0, time.UTC)
47 if err := os.Chtimes("some-filename", atime, mtime); err != nil {
48 log.Fatal(err)
52 func ExampleFileMode() {
53 fi, err := os.Lstat("some-filename")
54 if err != nil {
55 log.Fatal(err)
58 switch mode := fi.Mode(); {
59 case mode.IsRegular():
60 fmt.Println("regular file")
61 case mode.IsDir():
62 fmt.Println("directory")
63 case mode&os.ModeSymlink != 0:
64 fmt.Println("symbolic link")
65 case mode&os.ModeNamedPipe != 0:
66 fmt.Println("named pipe")
70 func ExampleIsNotExist() {
71 filename := "a-nonexistent-file"
72 if _, err := os.Stat(filename); os.IsNotExist(err) {
73 fmt.Printf("file does not exist")
75 // Output:
76 // file does not exist
79 func init() {
80 os.Setenv("USER", "gopher")
81 os.Setenv("HOME", "/usr/gopher")
82 os.Unsetenv("GOPATH")
85 func ExampleExpandEnv() {
86 fmt.Println(os.ExpandEnv("$USER lives in ${HOME}."))
88 // Output:
89 // gopher lives in /usr/gopher.
92 func ExampleLookupEnv() {
93 show := func(key string) {
94 val, ok := os.LookupEnv(key)
95 if !ok {
96 fmt.Printf("%s not set\n", key)
97 } else {
98 fmt.Printf("%s=%s\n", key, val)
102 show("USER")
103 show("GOPATH")
105 // Output:
106 // USER=gopher
107 // GOPATH not set
110 func ExampleGetenv() {
111 fmt.Printf("%s lives in %s.\n", os.Getenv("USER"), os.Getenv("HOME"))
113 // Output:
114 // gopher lives in /usr/gopher.
117 func ExampleUnsetenv() {
118 os.Setenv("TMPDIR", "/my/tmp")
119 defer os.Unsetenv("TMPDIR")