-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdemo3_io_read.go
executable file
·70 lines (61 loc) · 1.41 KB
/
demo3_io_read.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
65
66
67
68
69
70
package main
import (
"fmt"
"io"
//"io/ioutil"
"os"
)
func main() {
fileName := "E:/GoPath/src/a/aa.txt"
file, err := os.Open(fileName)
if err != nil {
fmt.Println("err: ", err)
return
}
//可以用defer先关闭掉,以防漏写,造成资源泄露
defer file.Close()
//ioutil.ReadDir()
//ioutil.ReadFile()
//ioutil.WriteFile()
//ioutil.Discard()
//ioutil.TempDir("", "go-build")
//读取数据
bs := make([]byte, 4, 4)
n := -1
for {
n, err = file.Read(bs)
if n == 0 || err == io.EOF{
fmt.Println("到了文件末尾,结束读取...")
break
}
fmt.Println(string(bs[:n]))
}
////第一次读取
//n, err := file.Read(bs)
//fmt.Println(err)//<nil>
//fmt.Println(n)//4
//fmt.Println(bs)//[97 115 100 102]返回的是每个元素的字节编码数值
//fmt.Println(string(bs))//asdf
//
////第二次读取
//n, err = file.Read(bs)
//fmt.Println(err)//<nil>
//fmt.Println(n)//4
//fmt.Println(bs)//[103 114 121 117]返回的是每个元素的字节编码数值
//fmt.Println(string(bs))//gryu
//
////第三次读取
//n, err = file.Read(bs)
//fmt.Println(err)//<nil>
//fmt.Println(n)//2
//fmt.Println(bs)//[105 111 121 117]返回的是每个元素的字节编码数值
//fmt.Println(string(bs))//ioyu
//
//
////第四次读取
//n, err = file.Read(bs)
//fmt.Println(err)//EOF
//fmt.Println(n)//0
//data := []byte("C语言中文网")
//rd := bytes.NewReader(data)
}