Golang : Test file read write permission example
Problem :
You need to test if a file has the correct write or read permission before performing write or read operation. How to do that?
Solution :
Use os.OpenFile()
function and check the error with os.IsPermission() to see if a file has permission denied error.
For example :
To test if a file has write permission : (do not run this program as root or super user)
package main
import (
"fmt"
"os"
)
func main() {
fileName := "file.txt"
file, err := os.OpenFile(fileName, os.O_WRONLY, 0666)
if err != nil {
if os.IsPermission(err) {
fmt.Println("Unable to write to ", fileName)
fmt.Println(err)
os.Exit(1)
}
}
file.Close()
}
To test if a file has read permission : (do not run this program as root or super user)
package main
import (
"fmt"
"os"
)
func main() {
fileName := "file.txt"
file, err = os.OpenFile(fileName, os.O_RDONLY, 0666)
if err != nil {
if os.IsPermission(err) {
fmt.Println("Unable to read from ", fileName)
fmt.Println(err)
os.Exit(1)
}
}
file.Close()
}
References :
https://golang.org/pkg/os/#IsPermission
https://www.socketloop.com/tutorials/golang-check-if-a-file-exist-or-not
See also : Golang : Get file permission
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.2k PHP : Get client IP address
+13.9k Golang : Get current time
+16.4k Golang : Test floating point numbers not-a-number and infinite example
+5k Golang : micron to centimeter example
+31.5k Golang : Example for ECDSA(Elliptic Curve Digital Signature Algorithm) package functions
+44.9k Golang : Use wildcard patterns with filepath.Glob() example
+23.7k Find and replace a character in a string in Go
+19.9k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+20.9k Golang : Convert PNG transparent background image to JPG or JPEG image
+7.7k Golang : Mapping Iban to Dunging alphabets
+14.1k Javascript : Prompt confirmation before exit