-1

How do I find and read line number something in a file that corresponds some input? I googled up this code, but it loads whole content of a file into single array with all the lines indexed. Isn't there simpler way?

func LinesInFile(fileName string) []string {
    f, _ := os.Open(fileName)
    // Create new Scanner.
    scanner := bufio.NewScanner(f)
    result := []string{}
    // Use Scan.
    for scanner.Scan() {
        line := scanner.Text()
        // Append line to result.
        result = append(result, line)
    }
    return result
}
  • 6
    Don't store and return lines you're not interested in. Just the one you need. Also see related: [How to read a file starting from a specific line number using Scanner?](https://stackoverflow.com/questions/34654514/how-to-read-a-file-starting-from-a-specific-line-number-using-scanner/34661512#34661512) – icza May 06 '20 at 12:38

1 Answers1

1

You should just ignore lines you're not interested.

func ReadExactLine(fileName string, lineNumber int) string {
    inputFile, err := os.Open(fileName)
    if err != nil {
        fmt.Println("Error occurred! ", err)
    }

    br := bufio.NewReader(inputFile)
    for i := 1; i < lineNumber; i++ {
        _, _ = br.ReadString('\n')
    }
    str, err := br.ReadString('\n')
    fmt.Println("Line is ", str)
    return str
}
Naser Erfani
  • 38
  • 1
  • 8