packagemainimport("fmt""os")funcmain(){f,err:=os.Create("$GOPATH/src/write/bytes")iferr!=nil{fmt.Println(err)return}// slice of bytesd2:=[]byte{104,101,108,108,111,32,119,111,114,108,100}n2,err:=f.Write(d2)iferr!=nil{fmt.Println(err)f.Close()return}fmt.Println(n2,"bytes written successfully")err=f.Close()iferr!=nil{fmt.Println(err)return}}// 11 bytes written successfully
packagemainimport("fmt""os")funcmain(){f,err:=os.Create("lines")iferr!=nil{fmt.Println(err)f.Close()return}d:=[]string{"Welcome to the world of Go1.","Go is a compiled language.","It is easy to learn Go."}for_,v:=ranged{// Fprintln formats using the default formats for its operands and writes to w. Spaces are always added between operands and a newline is appendedfmt.Fprintln(f,v)iferr!=nil{fmt.Println(err)return}}err=f.Close()iferr!=nil{fmt.Println(err)return}fmt.Println("file written successfully")}// file written successfully
packagemainimport("fmt""os")funcmain(){// open the file in append and write only mode// 0644 權限 -rw-r--r--f,err:=os.OpenFile("lines",os.O_APPEND|os.O_WRONLY,0644)iferr!=nil{fmt.Println(err)return}newLine:="File handling is easy."// Fprintln formats using the default formats for its operands and writes to w. Spaces are always added between operands and a newline is appended_,err=fmt.Fprintln(f,newLine)iferr!=nil{fmt.Println(err)f.Close()return}err=f.Close()iferr!=nil{fmt.Println(err)return}fmt.Println("file appended successfully")}// file appended successfully