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
+13.2k Golang : How to get a user home directory path?
+11.6k Swift : Convert (cast) Float to String
+12k Golang : How to parse plain email text and process email header?
+9.1k Golang : Inject/embed Javascript before sending out to browser example
+6.3k Golang : Extract sub-strings
+8.9k Golang : HTTP Routing with Goji example
+18.8k Unmarshal/Load CSV record into struct in Go
+9.2k Golang : Get curl -I or head data from URL example
+16.4k Golang : How to extract links from web page ?
+13.6k Golang : Count number of runes in string
+8.5k Your page has meta tags in the body instead of the head
+12.6k Golang : Forwarding a local port to a remote server example