Menu Close

Go – How to get the current working directory in go golang

In this tutorial, We are going to learn about how to get the current working directory in go golang.

We can get current working directory using Getwd() function in os package in go golang.

Getwd() function returns a rooted path name corresponding to the current working directory.

If It is possible to reach current working directory via multiple paths (due to symbolic links) then Getwd() function may return any one of them.

Getwd() function prototype:

func Getwd() (dir string, err error) 

Return Type:

  • dir : Current working directory path
  • err : An error value, which will be nil if the operation was successful, or an error otherwise.

Example:

package main

import (
    "fmt"
    "os"
)

func main() {
    wd, err := os.Getwd()
    
    if err != nil {
        fmt.Println("Error:", err)
    } else {
        fmt.Println("Working directory:", wd)
    }
}

In this example, we import the os and fmt packages. We then call os.Getwd() and store the results in wd and err. We then check if err is nil (indicating there was no error), and print the working directory to the console using fmt.Println().

Common errors:

There are a few common errors that can occur when using os.Getwd(). The most common is that the function returns an error, indicating that there was a problem retrieving the working directory. This can happen if the program does not have permission to access the current working directory, or if the current working directory does not exist.

Another error that can occur is that the program may return an empty string for the working directory. This can happen if the program is unable to determine the current working directory for some reason.

Output:

Working directory: /Users/John/go-workspace/src/main 

To learn more about golang, You can refer given below link:

https://www.techieindoor.com/go-lang-tutorial/
https://www.techieindoor.com/go-lang-tutorial/

References:

https://golang.org/doc/
https://golang.org/pkg/
https://golang.org/pkg/fmt/
https://golang.org/pkg/fmt/#Println
Posted in golang, os, packages

Leave a Reply

Your email address will not be published. Required fields are marked *