ADVERTISEMENT
ADVERTISEMENT

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

Parameter(s):

  • 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 »


ADVERTISEMENT




ADVERTISEMENT



Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.