1

Как получить путь к файлу и сам файл? Код:

import (
    "fmt"
    "log"
    "os"
    "path/filepath"
)

func main() {
    dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
    if err != nil {
            log.Fatal(err)
    }
    fmt.Println(dir)
}

Данный код получает только текущую директорию, но не файл! Как мне получить директорию и текущий запущенный файл? То есть что-то типо такого должно быть: C:\program\program.exe

0

2 ответа 2

2

Для этого есть функция Executable из стандартного пакета os.

Описание:

Executable returns the path name for the executable that started the current process. There is no guarantee that the path is still pointing to the correct executable. If a symlink was used to start the process, depending on the operating system, the result might be the symlink or the path it pointed to. If a stable result is needed, path/filepath.EvalSymlinks might help. Executable returns an absolute path unless an error occurred. The main use case is finding resources located relative to an executable. Executable is not supported on nacl.

1

Если проблема только в том что получается папка - просто уберите вызов filepath.Dir - этой функцией вы как раз отрезаете из пути имя файла и оставляете только папку.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.