×

Golang Tutorial

Golang Reference

Golang Programs

Golang Practice

Golang Miscellaneous

Golang os.Chmod() Function with Examples

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

os.Chmod()

In the Go language, the os package provides a platform-independent interface to operating system (Unix-like) functionality. The Chmod() function is an inbuilt function of the os package, it is used to change the mode of the named file to mode. If the file is a symbolic link, it changes the mode of the link's target. If there is an error, it will be of type *PathError.

It accepts two parameters (name string, mode FileMode) and returns <nil> if there is no error; otherwise, it returns an error.

Syntax

func Chmod(name string, mode FileMode) error

Parameters

  • name - File's name
  • FileMode - File's mode (permission) to define

Return Value

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

Example

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

package main

import (
	"fmt"
	"log"
	"os"
)

func main() {
	// Creating a new file
	new, err := os.Create("test.txt")
	if err != nil {
		log.Fatal(err)
	}
	defer new.Close()

	// Getting permission of the file
	stats, err := os.Stat("test.txt")
	if err != nil {
		log.Fatal(err)
	}
	// Printing the permissions
	fmt.Printf("Before changing the permission: %s\n",
		stats.Mode())

	// Using the Chmod() function
	// Changing the file's permission
	err = os.Chmod("test.txt", 0700)
	if err != nil {
		log.Fatal(err)
	}

	// Again, getting and printing the
	// permission of the file
	stats, err = os.Stat("test.txt")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("After changing the permission: %s\n",
		stats.Mode())
}

Output:

Before changing the permission: -rw-r--r--
After changing the permission: -rwx------

Golang os Package »




Comments and Discussions!

Load comments ↻





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