Skip to content

Instantly share code, notes, and snippets.

@ElMostafaIdrassi
Forked from tomcatzh/readwrite.go
Created September 1, 2020 14:39
Show Gist options
  • Save ElMostafaIdrassi/e5b1ab22a43b3c7a4e7b2ffb5ee7a380 to your computer and use it in GitHub Desktop.
Save ElMostafaIdrassi/e5b1ab22a43b3c7a4e7b2ffb5ee7a380 to your computer and use it in GitHub Desktop.
Golang readline and writeline
func readLines(path string) ([]string, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return lines, scanner.Err()
}
// writeLines writes the lines to the given file.
func writeLines(lines []string, path string) error {
file, err := os.Create(path)
if err != nil {
return err
}
defer file.Close()
w := bufio.NewWriter(file)
for _, line := range lines {
fmt.Fprintln(w, line)
}
return w.Flush()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment