Skip to content

Instantly share code, notes, and snippets.

@AntiKnot
Created January 16, 2022 14:21
Show Gist options
  • Select an option

  • Save AntiKnot/40cb0d460b6e7df21c74fb6a76871ecc to your computer and use it in GitHub Desktop.

Select an option

Save AntiKnot/40cb0d460b6e7df21c74fb6a76871ecc to your computer and use it in GitHub Desktop.
go read and write file; IO file
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