Read a file (stdin) line by line

yourbasic.org/golang

From file

Use a bufio.Scanner to read a file line by line.

file, err := os.Open("file.txt")
if err != nil {
    log.Fatal(err)
}
defer file.Close()

scanner := bufio.NewScanner(file)
for scanner.Scan() {
    fmt.Println(scanner.Text())
}

if err := scanner.Err(); err != nil {
    log.Fatal(err)
}

From stdin

Use os.Stdin to read from the standard input stream.

scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
	fmt.Println(scanner.Text())
}

if err := scanner.Err(); err != nil {
	log.Println(err)
}

Further reading

For more advanced scanning, see the examples in the bufio.Scanner documentation.

Share this page: