The Wayback Machine - https://web.archive.org/web/20230216140722/https://www.geeksforgeeks.org/filepath-dir-function-in-golang-with-examples/
Skip to content
Related Articles
Open in App
Not now

Related Articles

filepath.Dir() Function in Golang With Examples

Improve Article
Save Article
  • Last Updated : 10 May, 2020
Improve Article
Save Article

In Go language, path package used for paths separated by forwarding slashes, such as the paths in URLs. The filepath.Dir() function in Go language used to return all the elements of the specified path except the last element. After dropping the final element, Dir calls Clean on the path and trailing slashes are removed. If the path is empty, Dir returns “.”. If the path consists entirely of separators, Dir returns a single separator. The returned path does not end in a separator unless it is the root directory. Moreover, this function is defined under the path package. Here, you need to import the “path/filepath” package in order to use these functions.

Syntax:

func Dir(path string) string

Here, ‘path’ is the specified path.

Return Value: It returns all the elements of the specified path except the last element.

Example 1:




// Golang program to illustrate the usage of
// filepath.Dir() function
  
// Including the main package
package main
  
// Importing fmt and path/filepath
import (
    "fmt"
    "path/filepath"
)
  
// Calling main
func main() {
  
    // Calling the Dir() function
    fmt.Println(filepath.Dir("/Geeks/GFG/gfg.org"))
    fmt.Println(filepath.Dir("/Geeks/GFG/gfg"))
    fmt.Println(filepath.Dir("/Geeks/GFG/gfg/"))
    fmt.Println(filepath.Dir("/GFG/gfg///"))
    fmt.Println(filepath.Dir("/gfg.org"))
    fmt.Println(filepath.Dir("gfg.org"))
}

Output:

/Geeks/GFG
/Geeks/GFG
/Geeks/GFG/gfg
/GFG/gfg
/
.

Example 2:




// Golang program to illustrate the usage of
// filepath.Dir() function
  
// Including the main package
package main
  
// Importing fmt and path/filepath
import (
    "fmt"
    "path/filepath"
)
  
// Calling main
func main() {
  
    // Calling the Dir() function
    fmt.Println(filepath.Dir(""))
    fmt.Println(filepath.Dir("."))
    fmt.Println(filepath.Dir("/"))
    fmt.Println(filepath.Dir("//"))
    fmt.Println(filepath.Dir("../gfg.org"))
  
}

Output:

.
.
/
/
..

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!