Golang program to set file permission

Here, we are going to learn how to set file permission in Golang (Go Language)?
Submitted by Nidhi, on April 06, 2021 [Last updated : March 04, 2023]

How to set file permission in Golang?

Problem Solution:

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.

Program/Source Code:

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

Golang code to set file permission

// 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 fmt, os 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.

Golang File Handling Programs »





Comments and Discussions!

Load comments ↻





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