-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathwriting-files.go
More file actions
42 lines (35 loc) · 866 Bytes
/
writing-files.go
File metadata and controls
42 lines (35 loc) · 866 Bytes
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
package main
import (
"bufio"
"fmt"
"io/ioutil"
"os"
)
func check(e error) {
if e != nil {
panic(e)
}
}
func main() {
d1 := []byte("hello\ngo\n")
// To start, here’s how to dump a string (or just bytes) into a file.
err := ioutil.WriteFile("/tmp/dat1", d1, 0644)
check(err)
f, err := os.Create("/tmp/dat2")
check(err)
// It’s idiomatic to defer a Close immediately after opening a file.
defer f.Close()
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("hallo\n")
fmt.Printf("wrote %d bytes\n", n3)
f.Sync()
w := bufio.NewWriter(f)
n4, err := w.WriteString("buffered\n")
fmt.Printf("wrote %d bytes\n", n4)
// Use Flush to ensure all buffered operations have been applied to the underlying writer.
w.Flush()
}