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

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 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 {

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


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


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!





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

© some rights reserved.