In Go, you can handle and log errors when working with file I/O using the following steps:
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()
// 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)
}
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()
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.