Golang os.Chdir() Function

Golang os.Chdir() function is used to change the current working directory to the named directory.” If there is an error, it will be of type *PathError.

Syntax

func Chdir(dir string) error

Parameters

dir(string): The name of the directory to which you want to change the current working directory.

Return value

If successful, Chdir() returns nil. If there’s an error, it returns a non-nil error.

Example 1: How to Use os.Chdir() function

package main

import (
  "fmt"
  "os"
)

func main() {
  // Getting the current working directory
  initialDir, _ := os.Getwd()
  fmt.Println("Initial Directory:", initialDir)

  // Changing the current working directory to /tmp
  err := os.Chdir("/tmp")
  if err != nil {
    fmt.Println("Error:", err)
    return
  }

  // Getting the new current working directory
  newDir, _ := os.Getwd()
  fmt.Println("New Directory:", newDir)
}

Output

How to Use os.Chdir() function

When you run the above code, it will print the initial working directory, change it to /tmp (or another directory if you modify the code), and then print the new working directory.

Example 2: Change the Directory and List the Files

package main

import (
  "fmt"
  "io/ioutil"
  "os"
)

func main() {
  targetDir := "/tmp"

  // Change the current working directory to the target directory
  err := os.Chdir(targetDir)
  if err != nil {
    fmt.Println("Error changing directory:", err)
    return
  }

  // List all files in the new directory
  files, err := ioutil.ReadDir(targetDir)
  if err != nil {
    fmt.Println("Error reading directory:", err)
    return
  }

  fmt.Println("Files in", targetDir, ":")
  for _, file := range files {
    fmt.Println(" -", file.Name())
  }
}

Output

Change the Directory and List the Files

Example 3: Nested Directory Change

package main

import (
  "fmt"
  "os"
)

func main() {
  targetDir := "/tmp"

  // Change the current working directory to the target directory
  err := os.Chdir(targetDir)
  if err != nil {
    fmt.Println("Error changing directory:", err)
    return
  }

  // Navigate one directory deeper (assuming a directory named 'example' exists)
  err = os.Chdir("example")
  if err != nil {
    fmt.Println("Error changing to nested directory:", err)
    return
  }

  // Print the current directory
  currentDir, _ := os.Getwd()
  fmt.Println("Current Directory:", currentDir)
}

Output

Error changing to nested directory: chdir example: no such file or directory

That’s it!

Related posts

Golang os.Getenv()

Golang os.Lstat()

Golang os.Stat()

Golang os.Exit()

Leave a Comment