Skip to main content
Published on

Files (Read) in Go

Share:

Introduction

Reading files is one of the most common operations in programming. Whether for configurations, persistent data, or processing, reading files is fundamental. Go, with its practical and efficient approach, provides several libraries and functions to make this task easier.

Read the Entire File

One of the simplest ways to read a file in Go is to use the ioutil.ReadFile function.

import (
  "fmt"
  "io/ioutil"
)

func main() {
  content, err := ioutil.ReadFile("example.txt")

  if err != nil {
    fmt.Println("Error:", err)
    return
  }

  fmt.Println(string(content))
}

Reading with the "os" Package

For more granular control over reading, we can use the os package:

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

func main() {
  file, err := os.Open("example.txt")

  if err != nil {
    fmt.Println("Error:", err)
    return
  }

  defer file.Close()

  scanner := bufio.NewScanner(file)

  for scanner.Scan() {
    fmt.Println(scanner.Text())
  }

  if err := scanner.Err(); err != nil {
    fmt.Println("Read error:", err)
  }
}

Read Line by Line

For large files, reading line by line can be more efficient:

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

func readFileLineByLine(fileName string) error {
  file, err := os.Open(fileName)

  if err != nil {
    return err
  }

  defer file.Close()

  scanner := bufio.NewScanner(file)

  for scanner.Scan() {
    fmt.Println(scanner.Text())
  }

  return scanner.Err()
}

Conclusion

Reading files in Go is an intuitive task thanks to the language's modular approach and the libraries provided. Regardless of the complexity of your needs, Go has the tools to help you work with files effectively.

Happy coding!