You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
@@ -44,16 +43,17 @@ You can see `test.txt` contains `4` lines.
44
43
}
45
44
}
46
45
46
+
47
47
(a)
48
48
49
-
p, err := ioutil.ReadFile("test.txt")
50
-
`ioutil.ReadFile("test.txt")` reads the whole content of `test.txt`into a slice: `p`.
49
+
f, err := os.Open("test.txt")
50
+
Open `test.txt`file.
51
51
52
52
(b)
53
53
54
-
r := bufio.NewReader(bytes.NewReader(p))
54
+
r := bufio.NewReader(f)
55
55
56
-
`bufio.NewReader(bytes.NewReader(p))` creates a [bufio.Reader](https://golang.org/pkg/bufio/#Reader) struct which implements buffered read function.
56
+
`bufio.NewReader(f)` creates a [bufio.Reader](https://golang.org/pkg/bufio/#Reader) struct which implements buffered read function.
57
57
58
58
(c)
59
59
@@ -83,19 +83,18 @@ We can also use [bufio.Scanner](https://golang.org/pkg/bufio/#Scanner) to implem
83
83
84
84
import (
85
85
"bufio"
86
-
"bytes"
87
86
"fmt"
88
-
"io/ioutil"
89
87
"log"
88
+
"os"
90
89
)
91
90
92
91
func main() {
93
-
p, err := ioutil.ReadFile("test.txt")
92
+
f, err := os.Open("test.txt")
94
93
if err != nil {
95
94
log.Fatal(err)
96
95
}
97
96
98
-
s := bufio.NewScanner(bytes.NewReader(p))
97
+
s := bufio.NewScanner(f)
99
98
100
99
for s.Scan() {
101
100
fmt.Println(s.Text())
@@ -105,8 +104,8 @@ We can also use [bufio.Scanner](https://golang.org/pkg/bufio/#Scanner) to implem
105
104
106
105
(a)
107
106
108
-
s := bufio.NewScanner(bytes.NewReader(p))
109
-
`bufio.NewScanner(bytes.NewReader(p))` creates a new [bufio.Scanner](https://golang.org/pkg/bufio/#Scanner) struct which splits the content by line by default.
107
+
s := bufio.NewScanner(f)
108
+
`bufio.NewScanner(f)` creates a new [bufio.Scanner](https://golang.org/pkg/bufio/#Scanner) struct which splits the content by line by default.
110
109
111
110
(b)
112
111
@@ -118,22 +117,21 @@ We can also use [bufio.Scanner](https://golang.org/pkg/bufio/#Scanner) to implem
118
117
We can also customize [SplitFunc](https://golang.org/pkg/bufio/#SplitFunc) function which doesn't separate content by line. Check the following code:
0 commit comments