← Back to Go Course | Chapter 13: File IO & OS | Lesson 4 of 7

The bufio Package

bufio is like reading a long letter in whole sentences at a time instead of squinting at it one letter at a time -- it makes reading and writing much more efficient.
Syntax
go
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
    line := scanner.Text()
}

w := bufio.NewWriter(writer)
defer w.Flush()

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

markup
// Every Go file belongs to a package; main builds an executable
package main

// Import the packages this program uses
import (
	"bufio"
	"fmt"
	"strings"
)

// main is where the program starts running
func main() {
	// Short declaration: create text and infer the type
	text := "line one\nline two\nline three"
	// Short declaration: create scanner and infer the type
	scanner := bufio.NewScanner(strings.NewReader(text))
	// Repeat while scanner.Scan() is true
	for scanner.Scan() {
		// Print the values followed by a newline
		fmt.Println("read:", scanner.Text())
	}
}

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

markup
// Every Go file belongs to a package; main builds an executable
package main

// Import the packages this program uses
import (
	"bufio"
	"fmt"
	"os"
)

// main is where the program starts running
func main() {
	// Short declaration: create writer and infer the type
	writer := bufio.NewWriter(os.Stdout)
	writer.WriteString("buffered ")
	writer.WriteString("output\n")
	writer.Flush()
	// Print the values followed by a newline
	fmt.Println("flush complete")
}

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

markup
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))
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. 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.
  2. Forgetting to call Flush() on a bufio.Writer, leaving buffered data that never actually reaches the underlying file or connection.
  3. Assuming Scanner.Text() still holds the last line's data after calling Scan() again -- it's overwritten on each call.
Chapter Summary
  • 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.