Go
Read a file with Go
1package main2
3import (4 "bufio"5 "fmt"6 "log"7 "os"8)9
10func main() {11 f, err := os.Open("inputfile")12 if err != nil {13 log.Fatal(err)14 }15 defer f.Close()16
17 scanner := bufio.NewScanner(f)18 for scanner.Scan() {19 fmt.Println(scanner.Text())20 }21 if err := scanner.Err(); err != nil {22 log.Fatal(err)23 }24}
You could also:
- Use
ioutil.ReadFile
to read the whole file into memory. - Use a buffer with
bufio.NewReader
to read the file line by line.