Writing files in Go follows similar patterns to the ones we saw earlier for reading. |
|
package main
|
|
import (
"bufio"
"fmt"
"io/ioutil"
"os"
)
|
|
func check(e error) {
if e != nil {
panic(e)
}
}
|
|
func main() {
|
|
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)
check(err)
|
For more granular writes, open a file for writing. |
f, err := os.Create("/tmp/dat2")
check(err)
|
It’s idiomatic to defer a |
defer f.Close()
|
You can |
d2 := []byte{115, 111, 109, 101, 10}
n2, err := f.Write(d2)
check(err)
fmt.Printf("wrote %d bytes\n", n2)
|
A |
n3, err := f.WriteString("writes\n")
fmt.Printf("wrote %d bytes\n", n3)
|
Issue a |
f.Sync()
|
|
w := bufio.NewWriter(f)
n4, err := w.WriteString("buffered\n")
fmt.Printf("wrote %d bytes\n", n4)
|
Use |
w.Flush()
|
}
|
Try running the file-writing code. |
$ go run writing-files.go
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes
|
Then check the contents of the written files. |
$ cat /tmp/dat1
hello
go
$ cat /tmp/dat2
some
writes
buffered
|
Next we’ll look at applying some of the file I/O ideas
we’ve just seen to the |
Next example: Line Filters.