Created
January 16, 2022 14:21
-
-
Save AntiKnot/40cb0d460b6e7df21c74fb6a76871ecc to your computer and use it in GitHub Desktop.
go read and write file; IO file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "io/ioutil" | |
| "log" | |
| "os" | |
| ) | |
| func check(e error, s string) { | |
| if e != nil { | |
| log.Fatal(s) | |
| } | |
| } | |
| func read(filename string) string { | |
| file, err := os.Open(filename) | |
| check(err, fmt.Sprintf("cannot open %v", filename)) | |
| content, err := ioutil.ReadAll(file) | |
| check(err, fmt.Sprintf("cannot read %v", filename)) | |
| defer func() { | |
| if err = file.Close(); err != nil { | |
| log.Fatal(err) | |
| } | |
| }() | |
| return string(content) | |
| } | |
| func write(filename string, content string) { | |
| f, err := os.Create(filename) | |
| check(err, fmt.Sprintf("cannot create %v", filename)) | |
| _, err = f.WriteString(content) | |
| check(err, fmt.Sprintf("cannot write %v", filename)) | |
| defer func() { | |
| if err = f.Close(); err != nil { | |
| log.Fatal(err) | |
| } | |
| }() | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment