Golang Learning: Read and write files (for process edition)

Source: Internet
Author: User
Tags string to file
This is a creation in Article, where the information may have evolved or changed.
package main import  ("FMT" "Bufio" "IO" "OS" "Flag" "StrConv")//  use the command line  -in  The default is Infilevar in *string = flag. String ("in",  "infile",  "input file name  ...") var out *string =  Flag. String ("Out",  "outfile",  "output file name  ...") Func main ()  {//  Parse command line flag. Parse () Defer func ()  {//  If an exception is found ... if ex := recover (); nil!=ex {fmt. Println (Ex)}} () Value, err := read () if nil != err {//  throws Exception Panic (err)} Write (value)}func write (value []int)   (err error)  {//  Create file file, err2 :=  os. Create (*out) if nil != err2 {err = err2fmt. Println ("Error to create file ...") return}//  no matter what, finally close the file defer file. Close () for _, res := range value {//  convert int type to stringstr :=  StrConv. Itoa (res+2)//  writes a string to file in file. WriteString (str +  "\ n")}return nil}func read ()   (result []int, err  Error)  {//  open file File, err1 := os. Open (*in) if nil != err1 {err = err1return}//  no matter what, finally close the file defer file. Close ()//  creates a Bufferreaderbr := bufio from the file. Newreader (file)//  Initializes an array slice result = make ([]int, 0)//  the dead loop for {//  a line of read lines,  isprefix, err2 := br. ReadLine () if nil != err2 {//  read to the end of the file If io. Eof == err2 {fmt. Println ("finish read&nbsp ...")}return}if isprefix {break}//  converts a character array to a string str :=  String//  converts the string to Intvalue, err3 := strconv. Atoi (str) if nil != err3 {err = err3break}//  in a slice like result = append (Result, value)}   Returns the result return}


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.