I can get the current directory and the name of the current .go
file but if i build a .exe
from the file with go build
then i still get the .go
name.
.../Project/Test/testfile.go
After building testfile.go
with go build
i have these:
1) .../Project/Test/testfile.go
2) .../Project/Test/main.exe
When i execute main.exe i get testfile
But i want to get the main
name after executing main.exe
package main
import (
"errors"
"fmt"
"path/filepath"
"runtime"
"strings"
)
func GetFileName() string {
_, fpath, _, ok := runtime.Caller(0)
if !ok {
err := errors.New("failed to get filename")
panic(err)
}
filename := filepath.Base(fpath)
filename = strings.Replace(filename, ".go", "", 1)
return filename
}
func main() {
fmt.Print(GetFileName())
}
The os package provides os.Args[0]
to obtain the executable name, or if you want the whole path you could use os.Executable
, as @Peter has suggested