How to handle and log errors when working with file I/O in Go?

In Go, you can handle and log errors when working with file I/O using the following steps:

  1. Open the file using the os.Open() or os.Create() functions, depending on whether you want to read from or write to the file.
file, err := os.Open("filename.txt") if err != nil { log.Fatal(err) } defer file.Close()
  1. If the file is successfully opened, perform the necessary read or write operations. Make sure to check for errors during these operations.
// Read from the file data := make([]byte, 1024) n, err := file.Read(data) if err != nil { log.Fatal(err) } else { fmt.Printf("Read %d bytes from the file\n", n) } // Write to the file data := []byte("Hello, World!") n, err := file.Write(data) if err != nil { log.Fatal(err) } else { fmt.Printf("Wrote %d bytes to the file\n", n) }
  1. Use the defer statement to ensure that the file is closed after you finish working with it. This guarantees that the file will be closed even if an error occurs during the read or write operations.
defer file.Close()
  1. When handling errors, you can use the log package to log the error information. The log.Fatal() function logs the error message and terminates the program.
log.Fatal(err)

By logging errors and terminating the program in case of an error, you ensure that any issues with file I/O are properly identified and handled. Additionally, using the defer statement to close the file ensures that resources are properly released.