Created
August 28, 2018 05:39
-
-
Save jogam5/644027b920cfdbefa357e2df02bd1378 to your computer and use it in GitHub Desktop.
Go Read/Write Files
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 ( | |
"bufio" | |
"fmt" | |
"log" | |
"os" | |
) | |
// readLines reads a whole file into memory | |
// and returns a slice of its lines. | |
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() | |
} | |
func main() { | |
lines, err := readLines("foo.in.txt") | |
if err != nil { | |
log.Fatalf("readLines: %s", err) | |
} | |
for i, line := range lines { | |
fmt.Println(i, line) | |
} | |
if err := writeLines(lines, "foo.out.txt"); err != nil { | |
log.Fatalf("writeLines: %s", err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment