write to a file in go

Here's an example of how to write to a file in Go using the os and ioutil packages:

main.go
package main

import (
    "fmt"
    "io/ioutil"
    "os"
)

func main() {
    content := []byte("Hello, world!\n")
    fileErr := ioutil.WriteFile("output.txt", content, 0644)
    if fileErr != nil {
        fmt.Println("Error writing to file:", fileErr)
        os.Exit(1)
    }
    fmt.Println("File written successfully!")
}
329 chars
18 lines

In this example, we first create a byte slice with the content we want to write to the file. We then use the ioutil.WriteFile() function to write the content to a file called output.txt.

The 0644 parameter specifies the file permissions (read and write access for the owner, read-only access for all others). If the write operation is successful, the program outputs "File written successfully!". If an error occurs, the program will output "Error writing to file: " followed by a description of the error.

gistlibby LogSnag