Go read and write operations

Source: Internet
Author: User

Read and Write operations://Hello Project main.go/* reads data from a file, then sorts it, writes the sorted data to the new file */package mainimport ("FMT"//println () function in the FMT package) Bufio "" "IO" "OS" "StrConv" "" Sort ") Func readvalues (infile string) (values []int,err error) {file,err: = os. Open (infile) if err! = Nil {fmt. Println ("Open file failed!") ", infile)}defer file. Close () br: = Bufio. Newreader (file) values = make ([]int,0) For{line,isprefix,err1: = Br. ReadLine () if err1! = nil{if err1! = Io. Eof{err = Err1}break}if isprefix{fmt. Println ("A too long line, seems upexpected") Return}str: = string VALUE,ERR2: = StrConv. Atoi (str) if err2! = Nil{err = Err2return}values = Append (values,value)}return values,nil}func writevalues (values []int, outfile string) Error{file,err: = OS. Create (outfile) If err! = nil{fmt. Println ("Failed to create file! ", outfile) return Err}defer file. Close () for _,value: = range Values{str: = StrConv. Itoa (value) file. WriteString (str+ "\ n")}return Nil}func Main () {values,err: = Readvalues ("Unsorted.dat") if err! = nil{fmt. PRINTLN (Err)}else{sort. Ints (values) writevalues (values, "sort. Dat ")}} 

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Go read and write operations

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.