Q:

Golang program to set file permission

belongs to collection: Golang File Handling Programs

0

In this program, we will set file permission with the help of os.Chmod() function and print file permission using Mode() function on the console screen.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to set file permission is given below. The given program is compiled and executed successfully.

// Golang program to set file permission

package main

import "os"
import "fmt"

func main() {
	MyFile1, err1 := os.Stat("Sample.txt")
	if err1 != nil {
		fmt.Println("File does not exist")
	}
	fmt.Println("Before File Permissions:", MyFile1.Mode())

	err2 := os.Chmod("Sample.txt", 0444)
	if err2 != nil {
		fmt.Println(err2)
	}

	MyFile2, err3 := os.Stat("Sample.txt")
	if err3 != nil {
		fmt.Println("File does not exist")
	}
	fmt.Println("After File Permissions:", MyFile2.Mode())
}

Output:

Before: File Permissions: -rw-rw-rw-
After: File Permissions: -r--r--r—

Explanation:

In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmtos packages then we can use a function related to the fmt and os package.

In the main() function, we assigned permission to the file using os.Chmod() function. Here, we printed file permission before and after changing the permission of the file.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Golang File Handling Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Golang program to change the ownership of the file... >>
<< Golang program to check a specified file is exists...