-
Notifications
You must be signed in to change notification settings - Fork 1
/
demo4_io_writer.go
executable file
·64 lines (52 loc) · 1.08 KB
/
demo4_io_writer.go
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package main
import (
"bufio"
"fmt"
"io/ioutil"
"log"
"os"
)
func main() {
fileName := "E:/GoPath/src/a/ab.txt"
//打开文件,注意是否有此文件
//file, err := os.Open(fileName)
//file, err := os.Create()
file, err := os.OpenFile(fileName, os.O_CREATE|os.O_WRONLY|os.O_APPEND, os.ModePerm)
if err != nil {
fmt.Println("err: ", err)
return
}
//file, err := os.Open("writeAt.txt")
//if err != nil {
// panic(err)
//}
//defer file.Close()
//writer := bufio.NewWriter(os.Stdout)
//writer.ReadFrom(file)
//writer.Flush()
//ioutil.ReadFile()
//关闭文件
defer file.Close()
//写入数据
//bs := []byte{65,66,67,68,69,70}
bs := []byte{97,98,99,100}
//n,err := file.Write(bs)
n,err := file.Write(bs[:2])
fmt.Println(n)
HandleErr(err)
file.WriteString("\n")
//直接写出字符串
n,err = file.WriteString("Hello world")
fmt.Println(n)
HandleErr(err)
file.WriteString("\n")
//切片也可以直接写入字符串
n,err = file.Write([]byte("totay"))
fmt.Println(n)
HandleErr(err)
}
func HandleErr(err error){
if err != nil {
log.Fatal(err)
}
}