Use the os.Getwd() function to get the current working directory as a string in Golang. The current 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.
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
Write a Golang program that prints the current directory in the console.
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
In this example, the os.Getwd() function is called, and the result is stored in the currentDirectory variable.
If there is an error, the error is printed to the console, and the program ends.
The current directory will be printed on the console if everything works fine.
Common errors
Permission denied
The permission error occurs when the process does not have sufficient permissions to access the current directory.
Path not found
The “path not found” error occurs when the current directory does not exist or has been deleted.
The compiler raises this error when the current directory is set to a location that no longer exists or if the process was started with a different working directory that has since been deleted.
System call failed
The “system call failed” error occurs when there is a failure in the underlying system call used to get the current directory.
Conclusion
You can use the os.Getwd() function in the os package to get the current directory in Golang. The os.Getwd() function returns a string representing the current working directory and an error value. If the call is successful, the error value will be nil.
That’s it.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Distributed and cloud computing and is an expert in Go Language.