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() { d1 := []byte("hello\ngo\n") err := ioutil.WriteFile("/tmp/dat", d1, 0644) check(err) f, err := os.Create("/tmp/dat") check(err) defer f.Close() d2 := []byte{115, 111, 109, 101, 10} n2, err := f.Write(d2) check(err) fmt.Println("wrote %d bytes\n", n2) n3, err := f.WriteString("writes\n") fmt.Println("wrote %d bytes\n", n3) f.Sync() w := bufio.NewWriter(f) n4, err := w.WriteString("buffered\n") fmt.Println("wrote %d bytes\n", n4) w.Flush() }
wrote %d bytes 5 wrote %d bytes 7 wrote %d bytes 9
总结 :
1 : ....
有疑问加站长微信联系(非本文作者)