bufio

https://pkg.go.dev/bufio

The bufio package in Go provides buffered I/O operations, allowing efficient reading and writing of data, especially when dealing with streams of data like files or network connections. Here's a simplified overview along with examples explaining its usage:

1. Reading from a file using bufio.Reader:

import (
    "bufio"
    "os"
)

func readFromFile(filename string) error {
    file, err := os.Open(filename)
    if err != nil {
        return err
    }
    defer file.Close()

    // Create a bufio.Reader to efficiently read from the file
    reader := bufio.NewReader(file)

    for {
        // Read bytes until newline or EOF
        line, err := reader.ReadString('\n')
        if err != nil {
            break // EOF or error
        }
        // Process the line
        // Example: fmt.Println(line)
    }

    return nil
}

2. Writing to a file using bufio.Writer:

3. Reading from standard input using bufio.Scanner:

4. Writing to standard output using bufio.Writer:

Last updated

Was this helpful?