Created
January 6, 2026 19:37
-
-
Save brandonhimpfen/245f323a55b75c7e173f713add919cac to your computer and use it in GitHub Desktop.
Read a file line-by-line in Go using bufio.Scanner (with basic error handling and flags for long lines).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "bufio" | |
| "fmt" | |
| "log" | |
| "os" | |
| ) | |
| // Read a file line-by-line using bufio.Scanner. | |
| // Notes: | |
| // - Scanner has a default token limit (64K). If you may have long lines, | |
| // increase the buffer size (shown below). | |
| func main() { | |
| if len(os.Args) < 2 { | |
| log.Fatalf("usage: %s <path-to-file>", os.Args[0]) | |
| } | |
| path := os.Args[1] | |
| f, err := os.Open(path) | |
| if err != nil { | |
| log.Fatalf("open file: %v", err) | |
| } | |
| defer f.Close() | |
| scanner := bufio.NewScanner(f) | |
| // Increase the scanner buffer in case lines are longer than 64K. | |
| // Adjust maxCapacity to your expected maximum line length. | |
| const maxCapacity = 1024 * 1024 // 1MB | |
| buf := make([]byte, 64*1024) // initial buffer size | |
| scanner.Buffer(buf, maxCapacity) | |
| lineNum := 0 | |
| for scanner.Scan() { | |
| lineNum++ | |
| line := scanner.Text() | |
| // Do something with the line | |
| fmt.Printf("%d: %s\n", lineNum, line) | |
| } | |
| if err := scanner.Err(); err != nil { | |
| log.Fatalf("scan error: %v", err) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment