Home >Backend Development >Golang >How to Read a File Starting from a Specific Line Number Using bufio.Scanner in Go?
Reading a File Starting from a Specific Line Number using Scanner
In Go, you can use a bufio.Scanner to read a file line by line. However, bufio.Scanner does not provide a built-in option to start reading from a specific line number.
Here's a way to extend bufio.Scanner with a custom SplitFunc that allows you to skip lines and start reading from a desired line number:
func scannerWithStartLine(input io.ReadSeeker, start int64) (*bufio.Scanner, error) { if _, err := input.Seek(start, 0); err != nil { return nil, err } scanner := bufio.NewScanner(input) scanner.Split(func(data []byte, atEOF bool) (n int, err error) { if atEOF && len(data) == 0 { return 0, io.EOF } for i := 0; i < len(data); i++ { if data[i] == '\n' { return i + 1, nil } } return 0, nil }) return scanner, nil }
This function takes an io.ReadSeeker (such as a file) and a starting line number, and returns a bufio.Scanner that skips lines until the starting line number is reached.
To use this extended bufio.Scanner, you can follow these steps:
Here's an example:
file, err := os.Open("input.txt") if err != nil { // Handle error } startLine := 5 scanner, err := scannerWithStartLine(file, startLine) if err != nil { // Handle error } for scanner.Scan() { fmt.Println(scanner.Text()) }
This code will read the lines of the file "input.txt" starting from line 5.
The above is the detailed content of How to Read a File Starting from a Specific Line Number Using bufio.Scanner in Go?. For more information, please follow other related articles on the PHP Chinese website!