create a file in go

To create a file in Go, you need to import the os package and call the Create() function, which takes the name of the file you want to create as an argument, and returns a pointer to a File object. Here's an example:

main.go
package main

import (
    "fmt"
    "os"
)

func main() {
    // create a file named "example.txt" in the current directory
    file, err := os.Create("example.txt")
    if err != nil {
        // if an error occurred while creating the file, print the error and exit
        fmt.Println(err)
        return
    }
    defer file.Close() // make sure to close the file at the end of the function

    // write some text to the file
    _, err = file.WriteString("Hello, world!")
    if err != nil {
        // if an error occurred while writing to the file, print the error and exit
        fmt.Println(err)
        return
    }
}
631 chars
26 lines

This code creates a new file named "example.txt" in the current directory, writes the string "Hello, world!" to it, then closes the file. If an error occurs at any point, the code prints the error and exits.

Note that it's important to always close the file when you're done with it, to free up system resources and make sure your changes are written to disk. You can use the defer keyword to make sure the file is closed automatically when the function exits, as shown in the example.

related categories

gistlibby LogSnag