Learning record: A little practice of reading and writing files in the Go language

Source: Internet
Author: User
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. )

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.