Golang program to create a temporary file


In Go programming language we can use ioutil.TempFile function to create a temporary file. To create a new temporary file in the default temporary directory, this program uses the ioutil. TempFile function. The directory in which the file should be created is the first argument to TempFile, and the pattern to use for the file name is the second argument. The pattern in this instance is "temp-*.txt," leading to a file name like "temp-123456789.txt".

Syntax

Ioutil.TempFile 

In Go programming language, this function is a part of ioutil package and is used to create a temporary file. A temporary file is used to store data temporarily for the time the program executes.

Algorithm

  • Step 1 − Create a package main and declare fmt(format package), io/ioutil and os package in the program where main produces executable codes and fmt helps in formatting input and output.

  • Step 2 − Make an ioutil.TempFile call to create a new temporary file.

  • Step 3 − Verify if an error was returned by the TempFile call. Print the error and go back if there was one.

  • Step 4 − When the program ends, delete the file using a postpone statement.

  • Step 5 − Contact the file to add some text to the file, use the WriteString function.

  • Step 6 − Verify if an error was returned by the WriteString method. Print the error and return back if there was one.

  • Step 7 − To close a file, use the Close method.

  • Step 8 − Verify to see if the Close call produced an error. Print the error and return back if there was one.

  • Step 9 − Print a message stating the temporary file's name and that it was created using fmt.Println() function where ln means new line.

Example

In this example we will use ioutil.TempFile function to implement the program of creating a temporary file.

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

func main() {
   // Create a temporary file
   file, errs := ioutil.TempFile("", "temp-*.txt")
   if errs != nil {
      fmt.Println(errs)
      return
   }
   defer os.Remove(file.Name())

   // Write some text to the file
   _, errs = file.WriteString("Temporary file contents")
   if errs != nil {
      fmt.Println(errs)
      return
   }

   // Close the file
   errs = file.Close()
   if errs != nil {
      fmt.Println(errs)
      return
   }
   fmt.Println("The temporary file is created:", file.Name())
}

Output

The temporary file is created: /tmp/temp-*.txt133535689

Conclusion

We executed the program of creating a temporary function using an example in which we used ioutil.TempFile function which is used to create a temporary function. Here, if the file is created success message is printed otherwise return statement is executed.

Updated on: 21-Feb-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements