Skip to content

Go Bufio Package

The bufio package (short for "Buffered I/O") provides a way to read and write data efficiently by using a buffer. Instead of making many small, slow requests to the disk or network, bufio groups them into one large batch.

1. Reading with Scanner

The Scanner is the easiest way to read text line-by-line.

package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    // Read from standard input (the keyboard)
    scanner := bufio.NewScanner(os.Stdin)

    fmt.Println("Enter some text:")
    for scanner.Scan() {
        line := scanner.Text()
        if line == "exit" {
            break
        }
        fmt.Println("You typed:", line)
    }

    if err := scanner.Err(); err != nil {
        fmt.Fprintln(os.Stderr, "reading error:", err)
    }
}

2. Reading with Reader

If you need more control (like reading up to a specific character), use bufio.Reader.

1
2
3
4
// Read first 5 bytes
reader := bufio.NewReader(os.Stdin)
b, _ := reader.Peek(5)
fmt.Printf("%s\n", b)

3. Writing with Writer

Buffered writing is much faster than standard writing. Note: You must call Flush() at the end to make sure all data is actually written.

package main

import (
    "bufio"
    "os"
)

func main() {
    f, _ := os.Create("test.txt")
    defer f.Close()

    w := bufio.NewWriter(f)
    w.WriteString("Buffered string\n")

    // Crucial step!
    w.Flush()
}

Why use bufio?

  1. Performance: Significantly reduces the number of expensive system calls.
  2. Convenience: Provides high-level functions like ReadString, ReadBytes, and Scan.
  3. Correctness: Handles complex split logic (like finding where one word ends and another begins) for you.