Thursday 16 May 2024

GO LANG create and write to a temp file

 package main


import (

"fmt"

"io/ioutil"

"os"

)


func main() {

// "" means the default tmp directory, linux/tmp

tempFile, err := ioutil.TempFile("", "example-")

if err != nil {

fmt.Println("Error creating temporary file:", err)

return

}

defer os.Remove(tempFile.Name()) // Defer deletion of the temporary file


// Set custom permissions for the temporary file// 421 (u,g,o)

err = os.Chmod(tempFile.Name(), 0644)

if err != nil {

fmt.Println("Error setting permissions for temporary file:", err)

return

}


// Write some data into the temporary file

data := []byte("Your data here\n")

_, err = tempFile.Write(data)

if err != nil {

fmt.Println("Error writing to temporary file:", err)

return

}


fmt.Println("Data written to temporary file successfully.")

}


No comments:

Post a Comment