Get file path of temporary file in Go
There are time when we need to know the exact file path of a temporary file. This is a a short tutorial on how to get the file path of a temporary file in Go.
gettempfilepath.go
package main
import (
"fmt"
"os"
"io/ioutil"
"path/filepath"
)
func main () {
file, err := ioutil.TempFile(os.TempDir(), "temp")
if err != nil {
panic(err)
}
fmt.Println("Temp File created!")
thepath, err := filepath.Abs(filepath.Dir(file.Name()))
if err != nil {
panic(err)
}
fmt.Println("The file path : ", thepath)
defer os.Remove(file.Name())
}
See also : Golang : Get current file path of a file or executable
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+7.1k Golang : alternative to os.Exit() function
+7k Golang : Calculate how many weeks left to go in a given year
+6.4k Golang : When to use make or new?
+12k Golang : Flush and close file created by os.Create and bufio.NewWriter example
+6.3k Golang : Totalize or add-up an array or slice example
+15.3k Golang : Get digits from integer before and after given position example
+23.2k Golang : minus time with Time.Add() or Time.AddDate() functions to calculate past date
+8.6k Golang : Sort lines of text example
+18.1k Golang : Read binary file into memory
+18.1k Golang : How to get hour, minute, second from time?
+9.8k Golang : Get login name from environment and prompt for password
+9.7k Golang : Convert octal value to string to deal with leading zero problem