forked from mkaz/working-with-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path07-read-write-file.go
43 lines (35 loc) · 967 Bytes
/
07-read-write-file.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* read-write-files.go
*
* Examples reading and writing to a file using io/ioutil
* See: http://golang.org/pkg/io/ioutil/
*
*/
package main
import (
"fmt"
"io/ioutil"
"log"
)
func main() {
filename := "./extras/rabbits.txt"
// read in file, one command loads file into content variable
// if an error occurs returns it as the second return value
// if no error, err will be nil
content, err := ioutil.ReadFile(filename)
if err != nil {
// log is a nifty little utility which can also output
// in this case, a fatal log will halt the program
log.Fatalln("Error reading file", filename)
}
// content returned as []byte not string
// so must cast to string first and then can display
fmt.Println(string(content))
// write back to new file
// see documentation for which methods take what type
outfile := "output.txt"
err = ioutil.WriteFile(outfile, content, 0644)
if err != nil {
log.Fatalln("Error writing file: ", err)
}
}