CodeToLive

File Handling in Go (Golang)

File handling in Go is straightforward and efficient. Go provides a rich set of functions in the os and io packages to work with files. This section covers everything from basic file operations to advanced techniques like error handling and working with directories.

Opening a File

Use the os.Open() function to open a file in read-only mode. Always check for errors after opening a file.


package main

import (
  "fmt"
  "os"
)

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

  // Read file content
  data := make([]byte, 100)
  count, err := file.Read(data)
  if err != nil {
    fmt.Println("Error:", err)
    return
  }
  fmt.Println(string(data[:count]))
}
      

Writing to a File

Use the os.Create() function to create or truncate a file, and then write to it using file.Write() or file.WriteString().


package main

import (
  "os"
)

func main() {
  file, err := os.Create("example.txt")
  if err != nil {
    panic(err)
  }
  defer file.Close()

  _, err = file.WriteString("Hello, Go!")
  if err != nil {
    panic(err)
  }
}
      

Reading and Writing with ioutil

The ioutil package provides convenient functions like ReadFile and WriteFile for quick file operations.


package main

import (
  "fmt"
  "io/ioutil"
)

func main() {
  // Reading a file
  data, err := ioutil.ReadFile("example.txt")
  if err != nil {
    panic(err)
  }
  fmt.Println(string(data))

  // Writing to a file
  err = ioutil.WriteFile("example.txt", []byte("Hello, ioutil!"), 0644)
  if err != nil {
    panic(err)
  }
}
      

File Modes

Go allows you to specify file modes when creating or opening files. Common modes include:


package main

import (
  "os"
)

func main() {
  file, err := os.OpenFile("example.txt", os.O_APPEND|os.O_WRONLY, 0644)
  if err != nil {
    panic(err)
  }
  defer file.Close()

  _, err = file.WriteString(" Appended text!")
  if err != nil {
    panic(err)
  }
}
      

Error Handling

Always handle errors when working with files. Use the errors package or fmt.Errorf to create custom error messages.


package main

import (
  "fmt"
  "os"
)

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

Working with Directories

Go provides functions to work with directories, such as os.Mkdir, os.ReadDir, and os.Remove.


package main

import (
  "fmt"
  "os"
)

func main() {
  // Create a directory
  err := os.Mkdir("example_dir", 0755)
  if err != nil {
    panic(err)
  }

  // List files in a directory
  files, err := os.ReadDir("example_dir")
  if err != nil {
    panic(err)
  }
  for _, file := range files {
    fmt.Println(file.Name())
  }

  // Remove a directory
  err = os.Remove("example_dir")
  if err != nil {
    panic(err)
  }
}
      

Best Practices

Next: Control Structures in Go