Home  >  Article  >  Backend Development  >  How to Read a File Starting from a Specific Line Number Using bufio.Scanner in Go?

How to Read a File Starting from a Specific Line Number Using bufio.Scanner in Go?

Susan Sarandon
Susan SarandonOriginal
2024-11-06 02:41:02663browse

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:

  1. Open the file and set the starting line number.
  2. Create a bufio.Scanner using the scannerWithStartLine function.
  3. Call scanner.Scan() to read lines from the file, starting from the specified line number.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn