91_Go基础_1_59 file.Write
1 package main 2 3 import ( 4 "fmt" 5 "log" 6 "os" 7 ) 8 9 func HandleErr(err error) { 10 if err != nil { 11 log.Fatal(err) 12 } 13 } 14 15 func main() { 16 /* 17 写入数据: 18 */ 19 20 fileName := "D:\\Go\\web2\\aa.txt" 21 file, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, os.ModePerm) 22 HandleErr(err) 23 defer file.Close() 24 25 // 写入数据 26 bs := []byte{97, 98, 99, 100} //a,b,c,d 27 n, err := file.Write(bs[:2]) // n,err := file.Write(bs) 28 fmt.Println(n) // 2 29 HandleErr(err) 30 file.WriteString("\n") 31 32 // 直接写入字符串 33 n, err = file.WriteString("HelloWorld") 34 fmt.Println(n) // 10 35 HandleErr(err) 36 37 file.WriteString("\n") 38 n, err = file.Write([]byte("today")) 39 fmt.Println(n) // 5 40 HandleErr(err) 41 42 }