This is a creation in Article, where the information may have evolved or changed.
Package Mainimport ("OS" "FMT" "Bufio" "Strings" "StrConv") func main () {F, _:=os. OpenFile ("A.txt", OS. O_rdonly, 0666) defer f.close () M:=bufio. Newreader (f) char:=0words:=0lines:=0for{s, ok:=m.readstring (' \ n ') fmt. Println (s) char+=len (s) words+=len (strings. Fields (s)) Lines++if ok!=nil{break}}fmt. Println ("Char:" +tostring (char) + ", Words:" +tostring (words) + ", Lines:" +tostring (lines))}func toString (a interface{}) string{if v,p:=a. (int);p {return StrConv. Itoa (v)}if v,p:=a. (float64); p{return StrConv. Formatfloat (V, ' f ',-1, +)}if v,p:=a. (float32); p {return StrConv. Formatfloat (Float64 (v), ' f ',-1, +)} if v,p:=a. (Int16); p { return StrConv. Itoa (int (v))} if v,p:=a. (uint); p { return StrConv. Itoa (int (v))} if V,p:=a. (int32); p { return StrConv. Itoa (int (v)))}return "Wrong"}
The main purpose of the program is to read a file, output to the screen, and output the word count, number of words, number of lines, this is a study from the "Go language" exercises.
F, _:=os. OpenFile ("A.txt", OS. O_rdonly, 0666) This sentence is to create a read-only file stream to A.txt (in fact I ask the master to call the file resource handle. I feel as if the flow is better understood, let me use the flow to describe it.
Defer F.close () uses the post-press statement defer in the go language to make sure that stream F is closed after this function ends.
M:=bufio. Newreader (f) a new buffer stream m is formed by wrapping a buffer pipe outside the F-stream to read.
S, ok:=m.readstring (' \ n ') m reads the file, pauses to read ' \ n ', returns the string that was read before
Strings. Does the fields (s) divide s according to the whitespace character to get a string array or a slice slice? (NN, this is not clear, it should be sliced, it seems to have to go back to study. )