read a file in go

To read a file in Go, you can use the built-in os and bufio packages. Here is an example code snippet that demonstrates how to read a file line by line:

main.go
package main

import (
    "bufio"
    "fmt"
    "os"
)

func main() {
    // Open the file for reading
    file, err := os.Open("file.txt")
    if err != nil {
        fmt.Println("Error opening file:", err)
        return
    }
    defer file.Close()

    // Create a new scanner and set the split function
    scanner := bufio.NewScanner(file)
    scanner.Split(bufio.ScanLines)

    // Read line by line
    for scanner.Scan() {
        line := scanner.Text()
        fmt.Println(line)
    }

    // Check for any errors during scanning
    if scanner.Err() != nil {
        fmt.Println("Error reading file:", scanner.Err())
        return
    }
}
652 chars
34 lines

In this example, we first open the file using os.Open(), which returns the file and an error (if any). We then create a new scanner using bufio.NewSaner() and set the split function to bufio.ScanLines so that the scanner reads the file line by line. We then loop through each line, printing it to the console, and finally check for any errors using scanner.Err(). It's also important to defer the closing of the file until the end of the function using defer file.Close().

gistlibby LogSnag