Languages: Python C C++ Go Java Ruby Rust Perl R ← Full TOC

← Go Index

📚 bufio — Buffered I/O — Scanner, Reader, Writer

Wraps an io.Reader or io.Writer to add buffering, which reduces the number of system calls and improves performance. bufio.Scanner is the idiomatic way to read a file line by line in Go.

Import: import "bufio" | Docs: pkg.go.dev/bufio

📋 Functions, Types & Constants

NameSignature / ValueDescription
bufio.NewReaderfunc NewReader(rd io.Reader) *ReaderCreate buffered reader with default 4096-byte buffer
bufio.NewReaderSizefunc NewReaderSize(rd io.Reader, size int) *ReaderCreate buffered reader with custom size
r.ReadStringfunc (b *Reader) ReadString(delim byte) (string, error)Read until delimiter (inclusive)
r.ReadLinefunc (b *Reader) ReadLine() (line []byte, isPrefix bool, err error)Read a single line
r.ReadBytefunc (b *Reader) ReadByte() (byte, error)Read and return a single byte
r.UnreadBytefunc (b *Reader) UnreadByte() errorUn-read the last byte read
r.Peekfunc (b *Reader) Peek(n int) ([]byte, error)Return next n bytes without advancing
bufio.NewWriterfunc NewWriter(w io.Writer) *WriterCreate buffered writer
bw.WriteStringfunc (b *Writer) WriteString(s string) (int, error)Write string to buffer
bw.Flushfunc (b *Writer) Flush() errorFlush buffered data to underlying writer
bw.WriteBytefunc (b *Writer) WriteByte(c byte) errorWrite single byte to buffer
bufio.NewScannerfunc NewScanner(r io.Reader) *ScannerCreate Scanner for convenient line-by-line reading
s.Scanfunc (s *Scanner) Scan() boolAdvance to next token; return false at EOF or error
s.Textfunc (s *Scanner) Text() stringReturn text of current token as string
s.Bytesfunc (s *Scanner) Bytes() []byteReturn current token as []byte (avoids allocation)
s.Errfunc (s *Scanner) Err() errorReturn first non-EOF error encountered
s.Splitfunc (s *Scanner) Split(split SplitFunc)Set split function (default: ScanLines)
bufio.ScanLinesfunc ScanLines(data []byte, atEOF bool) ...Split function for lines (strips \n)
bufio.ScanWordsfunc ScanWords(data []byte, atEOF bool) ...Split function for whitespace-delimited words
bufio.ScanBytesfunc ScanBytes(data []byte, atEOF bool) ...Split function for individual bytes
bufio.Scanner.Bufferfunc (s *Scanner) Buffer(buf []byte, max int)Set initial buffer and max token size

💡 Example Program

Save as main.go inside any directory and run with go run main.go. No extra packages to install — all standard library.

package main

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

func main() {
    // --- bufio.Scanner — read stdin line by line ---
    fmt.Println("=== Scanner from string ===")
    input := "line one\nline two\nline three\n"
    scanner := bufio.NewScanner(strings.NewReader(input))
    lineNum := 0
    for scanner.Scan() {
        lineNum++
        fmt.Printf("  %d: %s\n", lineNum, scanner.Text())
    }
    if err := scanner.Err(); err != nil {
        fmt.Fprintln(os.Stderr, "scan error:", err)
    }

    // --- bufio.Scanner — scan words ---
    fmt.Println("=== Word scanner ===")
    wordScan := bufio.NewScanner(strings.NewReader("Go is awesome"))
    wordScan.Split(bufio.ScanWords)
    for wordScan.Scan() {
        fmt.Printf("  word: %q\n", wordScan.Text())
    }

    // --- bufio.Writer — buffered file write ---
    fmt.Println("=== Buffered file write ===")
    f, _ := os.Create("buffered.txt")
    bw := bufio.NewWriter(f)
    for i := 1; i <= 5; i++ {
        fmt.Fprintf(bw, "Line %d: Go buffered I/O\n", i)
    }
    bw.Flush()  // IMPORTANT: flush before closing
    f.Close()

    // Read back with Scanner
    f2, _ := os.Open("buffered.txt")
    defer f2.Close()
    s2 := bufio.NewScanner(f2)
    for s2.Scan() {
        fmt.Println(" ", s2.Text())
    }
    os.Remove("buffered.txt")
}
// go run main.go

← sync  |  🏠 Index