Friday, May 17, 2024
HomeGolangMomentary file in Go (Golang)

Momentary file in Go (Golang)



While you write a program that processes massive quantities of knowledge, otherwise you take a look at a program that creates information, you typically want the power to create short-term information that assist you to retailer your information for a short while with out cluttering your venture’s disk house. In Go, you may create a brief file with os.CreateTemp() operate and a brief listing with os.MkdirTemp() operate.

os.CreateTemp() and os.MkdirTemp() can be found since Go 1.17. For older variations you need to use ioutil.TempFile() and ioutil.TempDir().

Create a brief file

package deal essential

import (
    "log"
    "os"
)

func essential() {
    // create and open a brief file
    f, err := os.CreateTemp("", "tmpfile-") // in Go model older than 1.17 you need to use ioutil.TempFile
    if err != nil {
        log.Deadly(err)
    }

    // shut and take away the short-term file on the finish of this system
    defer f.Shut()
    defer os.Take away(f.Identify())

    // write information to the short-term file
    information := []byte("abc abc abc")
    if _, err := f.Write(information); err != nil {
        log.Deadly(err)
    }
}

The operate func CreateTemp(dir, sample string) (*File, error) has two parameters:

  • dir which is a listing the place a brief file needs to be created. If left empty, the default listing for short-term information (for a given OS) is used.
  • sample that’s used to generate names of short-term information. The identify is created by appending a random string to the tip of the sample. On this approach, within the instance, we get names reminiscent of tmpfile-483140887. You can even use * to point the place the random string needs to be positioned. Giving tmpfile-*.txt you get, for instance, tmpfile-483140887.txt.

In case you don’t use the short-term file anymore, it’s a good follow to take away it utilizing os.Take away().

Create a brief listing

package deal essential

import (
    "fmt"
    "log"
    "os"
)

func essential() {
    // create a brief listing
    identify, err := os.MkdirTemp("", "dir") // in Go model older than 1.17 you need to use ioutil.TempDir
    if err != nil {
        log.Deadly(err)
    }

    // take away the short-term listing on the finish of this system
    defer os.RemoveAll(identify)

    // print path of the listing
    fmt.Println(identify)
}

Parameters of the func MkdirTemp(dir, sample string) (string, error) operate work the identical approach as within the case of os.CreateTemp(). As earlier than, after you end working with the short-term folder, it’s best to bear in mind to delete it, for instance, by way of os.RemoveAll.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments