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
+10.5k Golang : Byte format example
+16.8k Golang : Get all upper case or lower case characters from string example
+5.7k Golang : Find the longest line of text example
+18.8k Android Studio : AlertDialog and EditText to get user string input example
+8.6k Golang : Qt get screen resolution and display on center example
+11.5k Golang : Get absolute path to binary for os.Exec function with exec.LookPath
+9k Golang : Translate language with language package example
+4.1k Golang : Print instead of building pyramids
+18.6k Golang : How to count the number of repeated characters in a string?
+13k Golang : Google Drive API upload and rename example
+13.2k Golang : Send email with attachment(RFC2822) using Gmail API example
+3.8k Chrome : How to block socketloop.com links in Google SERP?