Go
Read a file with Go
Section titled “Read a file with Go”package main
import ( "bufio" "fmt" "log" "os")
func main() { f, err := os.Open("inputfile") if err != nil { log.Fatal(err) } defer f.Close()
scanner := bufio.NewScanner(f) for scanner.Scan() { fmt.Println(scanner.Text()) } if err := scanner.Err(); err != nil { log.Fatal(err) }}You could also:
- Use
ioutil.ReadFileto read the whole file into memory. - Use a buffer with
bufio.NewReaderto read the file line by line.