How to Get the Current Working Directory in Golang

To get the current working directory in Go, use the “os.Getwd()” or “filepath.Abs(‘.’)” function. The current working directory is the directory in which a process starts, and it is usually the directory in which the current program or executable file is located.

Method 1: Using the os.Getwd() function

The os.Getwd() function is used to “get the rooted pathname corresponding to the current directory”.

Syntax

func Getwd()(dir string, err error)

Parameters

The Getwd() function does not accept any parameter.

Return value

The return type of the os.Getwd() function is a string containing the rooted pathname corresponding to the current directory and an error, if any.

Example

package main

import (
  "fmt"
  "os"
)

func main() {
  currentDirectory, err := os.Getwd()
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println("The current directory is:", currentDirectory)
}

Output

The current directory is: /Users/krunallathiya/Desktop/Code/Go

Method 2: Using the filepath.Abs() function

You can also use the “path/filepath’s Abs()” function to get the current working directory in Go.

Syntax

func Abs(path string) (string, error)

Parameters

The “path” is the specified path.

Return value

It returns an absolute representation of the specified path.

Example

package main

import (
  "fmt"
  "path/filepath"
)

func main() {
 // Get the current working directory.
 currentDirectory, err := filepath.Abs(".")
 
 if err != nil {
   // Handle the error.
   panic(err)
 }

  // Print the current working directory.
fmt.Println("The current directory is:", currentDirectory)
}

Output

The current directory is: /Users/krunallathiya/Desktop/Code/Go

That’s it.

1 thought on “How to Get the Current Working Directory in Golang”

  1. I found that os.Getwd() gets the current directory of the source code file it is invoked from. I would like to know a reliable way of getting the users current directory, not the source code’s directory or the directory where the executable is located. I can’t find a reliable way to do this! In your example, I bet ‘/Users/krunallathiya/Desktop/Code/Go’ is the same location on disk where your main program is. If you navigate to a different directory and run the same program, what do you get?

    Reply

Leave a Comment