22

Read a file (stdin) line by line

 3 years ago
source link: https://yourbasic.org/golang/read-file-line-by-line/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Read a file (stdin) line by line

yourbasic.org/golang
boy-reading-book.png

Read 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)
}

Read 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)
}

Read from any stream

teddy-bear-reading-thumb.jpg

A bufio.Scanner can read from any stream of bytes, as long as it implements the io.Reader interface. See How to use the io.Reader interface.

Further reading

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

Share:             


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK