Creating & Writing to Temp Files

· 247 words · 2 minutes read

We programmers often use temporary files and this example shows how we can create and write to one. We used the ioutil package which has functions for just this.

The TempFile() accepts a folder and a prefix. As the folder we get the os’ temp directory (which would be /tmp on unix systems) and for the prefix we use a string, but if we don’t want one, we just pass an empty string.

The temp files won’t be removed until you say, so we use a defer call to delete the file once we’re finished with it, with os.Remove().

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package main

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

func main() {

    // Create our Temp File:  This will create a filename like /tmp/prefix-123456
    // We can use a pattern of "pre-*.txt" to get an extension like: /tmp/pre-123456.txt
    tmpFile, err := ioutil.TempFile(os.TempDir(), "prefix-")
    if err != nil {
        log.Fatal("Cannot create temporary file", err)
    }

    // Remember to clean up the file afterwards
    defer os.Remove(tmpFile.Name())

    fmt.Println("Created File: " + tmpFile.Name())

    // Example writing to the file
    text := []byte("This is a golangcode.com example!")
    if _, err = tmpFile.Write(text); err != nil {
        log.Fatal("Failed to write to temporary file", err)
    }

    // Close the file
    if err := tmpFile.Close(); err != nil {
        log.Fatal(err)
    }
}

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!