The bufio Package
In this page:
Reading Lines with bufio.Scanner
bufio.NewScanner wraps any io.Reader and, combined with bufio.ScanLines (the default), lets you read input one line at a time by repeatedly calling Scan() and reading Text().
Example: Reading Lines with bufio.Scanner
package main
import (
"bufio"
"fmt"
"strings"
)
func main() {
text := "line one\nline two\nline three"
scanner := bufio.NewScanner(strings.NewReader(text))
for scanner.Scan() {
fmt.Println("read:", scanner.Text())
}
}
Login to try C/C++/Java/PHP code in the editor
Buffered Writing with bufio.Writer
bufio.Writer batches small writes into an internal buffer, sending them to the underlying writer in fewer, larger chunks -- which is more efficient, but requires an explicit Flush() to guarantee everything is actually written out.
Note: Always call Flush() when you're done writing, or the last buffered bytes may never reach the destination.
Example: Buffered Writing with bufio.Writer
package main
import (
"bufio"
"fmt"
"os"
)
func main() {
writer := bufio.NewWriter(os.Stdout)
writer.WriteString("buffered ")
writer.WriteString("output\n")
writer.Flush()
fmt.Println("flush complete")
}
Login to try C/C++/Java/PHP code in the editor
Simulating Reading From Input
In a real interactive program, bufio.NewReader(os.Stdin) reads user input line by line, but since this sandbox has no live terminal input, the same bufio.Reader API is demonstrated here reading from an in-memory string instead.
Note: Judge0 has no interactive stdin, so this example simulates input with a string reader instead of os.Stdin.
Example: Simulating Reading From Input
package main
import (
"bufio"
"fmt"
"strings"
)
func main() {
// Simulated stdin content (real os.Stdin would be used interactively)
reader := bufio.NewReader(strings.NewReader("Gopher\n"))
name, _ := reader.ReadString('\n')
fmt.Println("hello,", strings.TrimSpace(name))
}
Login to try C/C++/Java/PHP code in the editor
- Using bufio.NewScanner on a single line that's longer than the scanner's default buffer size without increasing it, causing a silent truncation or error.
- Forgetting to call Flush() on a bufio.Writer, leaving buffered data that never actually reaches the underlying file or connection.
- Assuming Scanner.Text() still holds the last line's data after calling Scan() again -- it's overwritten on each call.
- bufio.Scanner reads input line by line (or by other split functions) efficiently.
- bufio.Reader/Writer wrap an io.Reader/Writer with an internal buffer to reduce the number of underlying I/O operations.
- A bufio.Writer's buffered data must be explicitly flushed with Flush() to guarantee it's actually written out.
- bufio is commonly used for reading files or (in interactive programs) reading from os.Stdin.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: