-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path57_writing_files.go
More file actions
49 lines (40 loc) · 1.13 KB
/
57_writing_files.go
File metadata and controls
49 lines (40 loc) · 1.13 KB
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
package gobyexample
import (
"bufio"
"fmt"
"io/ioutil"
"os"
)
// WriteFilesDemo - demonstrates writing files
func WriteFilesDemo() {
// 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)
check(err)
// For more granular writes, open a file for writing.
f, err := os.Create("/tmp/dat2")
check(err)
// It is 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)
check(err)
fmt.Printf("Wrote %d bytes\n", n2)
// A `WriteString` is also available.
n3, err := f.WriteString("writes\n")
check(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")
check(err)
fmt.Printf("Wrote %d bytes\n", n4)
// Use `Flush` to ensure all buffered operations have been applied
// to the underlying writer.
w.Flush()
}