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.
14 func ExampleOpenFile() {
15 f, err := os.OpenFile("notes.txt", os.O_RDWR|os.O_CREATE, 0755)
19 if err := f.Close(); err != nil {
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)
30 if _, err := f.Write([]byte("appended some data\n")); err != nil {
33 if err := f.Close(); err != nil {
39 if err := os.Chmod("some-filename", 0644); err != nil {
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 {
52 func ExampleFileMode() {
53 fi, err := os.Lstat("some-filename")
58 fmt.Printf("permissions: %#o\n", fi.Mode().Perm()) // 0400, 0777, etc.
59 switch mode := fi.Mode(); {
60 case mode.IsRegular():
61 fmt.Println("regular file")
63 fmt.Println("directory")
64 case mode&os.ModeSymlink != 0:
65 fmt.Println("symbolic link")
66 case mode&os.ModeNamedPipe != 0:
67 fmt.Println("named pipe")
71 func ExampleIsNotExist() {
72 filename := "a-nonexistent-file"
73 if _, err := os.Stat(filename); os.IsNotExist(err) {
74 fmt.Println("file does not exist")
77 // file does not exist
80 func ExampleExpand() {
81 mapper := func(placeholderName string) string {
82 switch placeholderName {
92 fmt.Println(os.Expand("Good ${DAY_PART}, $NAME!", mapper))
95 // Good morning, Gopher!
98 func ExampleExpandEnv() {
99 os.Setenv("NAME", "gopher")
100 os.Setenv("BURROW", "/usr/gopher")
102 fmt.Println(os.ExpandEnv("$NAME lives in ${BURROW}."))
105 // gopher lives in /usr/gopher.
108 func ExampleLookupEnv() {
109 show := func(key string) {
110 val, ok := os.LookupEnv(key)
112 fmt.Printf("%s not set\n", key)
114 fmt.Printf("%s=%s\n", key, val)
118 os.Setenv("SOME_KEY", "value")
119 os.Setenv("EMPTY_KEY", "")
128 // MISSING_KEY not set
131 func ExampleGetenv() {
132 os.Setenv("NAME", "gopher")
133 os.Setenv("BURROW", "/usr/gopher")
135 fmt.Printf("%s lives in %s.\n", os.Getenv("NAME"), os.Getenv("BURROW"))
138 // gopher lives in /usr/gopher.
141 func ExampleUnsetenv() {
142 os.Setenv("TMPDIR", "/my/tmp")
143 defer os.Unsetenv("TMPDIR")