-
Notifications
You must be signed in to change notification settings - Fork 26
/
writing-files.go
54 lines (45 loc) · 1.26 KB
/
writing-files.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
44
45
46
47
48
49
50
51
52
53
54
package main
import (
"bufio"
"fmt"
"io/ioutil"
"os"
)
/*
Writing files in Go follows similar patterns to the ones
we saw earlier for reading.
*/
func checkWrite(e error) {
if e != nil {
panic(e)
}
}
// WriteFiles illustrate writing files in go.
func WriteFiles() {
// To start, here’s how to dump a string (or just bytes) into a file.
d1 := []byte("hello\ngo\n")
err := ioutil.WriteFile("/tmp/dat1", d1, 0644)
checkWrite(err)
// For more granular writes, open a file for writing.
f, err := os.Create("/tmp/dat2")
checkWrite(err)
// It’s idiomatic to defer a Close immediately after opening a file.
defer f.Close()
// You can Write byte slices as you’d expect.
d2 := []byte{115, 111, 109, 101, 10}
n2, err := f.Write(d2)
checkWrite(err)
fmt.Printf("wrote %d bytes\n", n2)
// A WriteString is also available.
n3, err := f.WriteString("writes\n")
checkWrite(err)
fmt.Printf("wrote %d bytes\n", n3)
// Issue a Sync to flush writes to stable storage.
f.Sync()
// bufio provides buffered writers in addition to the buffered readers we saw earlier.
w := bufio.NewWriter(f)
n4, err := w.WriteString("buffered\n")
fmt.Printf("wrote %d bytes\n", n4)
w.Flush()
// Use Flush to ensure all buffered operations have been applied to the underlying writer.
}