Golang os.Chdir() Function with Examples

Golang | os.Chdir() Function: Here, we are going to learn about the Chdir() function of the os package with its usages, syntax, and examples.
Submitted by IncludeHelp, on November 07, 2021

os.Chdir()

In the Go language, the os package provides a platform-independent interface to operating system (Unix-like) functionality. The Chdir() function is an inbuilt function of the os package, it is used to change the current working directory to the named directory. If there is an error, it will be of type *PathError.

It accepts one parameter (dir string) and returns <nil> if there is no error; otherwise, it returns an error.

Syntax:

func Chdir(dir string) error

Parameter(s):

  • dir : Directory name.

Return Value:

The return type of the os.Chdir() function is an error, it returns <nil> if there is no error; otherwise, it returns an error.

Example 1:

// Golang program to demonstrate the
// example of Chdir() function

package main

import (
	"fmt"
	"os"
)

func main() {
	// Changing the directory
	err := os.Chdir("/home/")
	// Getting current working directory
	cwd, _ := os.Getwd()

	// Printing the values
	fmt.Println("err:", err)
	fmt.Println("cwd:", cwd)
}

Output:

err: <nil>
cwd: /home

Example 2:

// Golang program to demonstrate the
// example of Chdir() function

package main

import (
	"fmt"
	"os"
)

func main() {
	// Getting current working directory
	CurDir, err := os.Getwd()
	if err != nil {
		panic(err)
	} else {
		fmt.Println("Current working directory: ", CurDir)
	}

	// Calling the function Chdir() to change the directory
	os.Chdir("/home/")

	// After changing the directory,
	// again getting current working directory

	CurDir, err = os.Getwd()
	if err != nil {
		panic(err)
	} else {
		fmt.Println("Current working directory: ", CurDir)
	}
}

Output:

Current working directory:  /
Current working directory:  /home

Golang os Package »




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.