Golang : Get current file path of a file or executable
Getting a file path in Golang is not that straight forward with just a single function call. In this tutorial, we will learn how to get the current file path of a file with filepath.Abs.
getfilepath.go
package main
import (
"fmt"
"log"
"os"
"path/filepath"
)
func main () {
filename := os.Args[1] // get command line first parameter
filedirectory := filepath.Dir(filename)
thepath, err := filepath.Abs(filedirectory)
if err != nil {
log.Fatal(err)
}
fmt.Println(thepath)
}
Executing > go run getfilepath.go somefile
will return the current path of the somefile
For finding out the executable file path. In most cases, os.Getwd should do the job.
You can use the above code as well to find the current path of the executing program. Just change the line
filename := os.Args[1] // get command line first parameter
to
filename := os.Args[0] // use own filename
Hope this tutorial can be useful to you.
References :
http://golang.org/pkg/path/filepath/
http://andrewbrookins.com/tech/golang-get-directory-of-the-current-file/
See also : Golang : File path independent of Operating System
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
+8.4k Linux/Unix : fatal: the Postfix mail system is already running
+13k Golang : How to calculate the distance between two coordinates using Haversine formula
+7.3k Golang : Check to see if *File is a file or directory
+7k Golang : Transform lisp or spinal case to Pascal case example
+18.9k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?
+4.9k Golang : Constant and variable names in native language
+6.9k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+36.3k Golang : Validate IP address
+9.4k Golang : How to extract video or image files from html source code
+7.4k Golang : How to stop user from directly running an executable file?
+33.9k Golang : Create x509 certificate, private and public keys