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
+35.5k Golang : Converting a negative number to positive number
+5.6k Golang : Use NLP to get sentences for each paragraph example
+17k Golang : Check if IP address is version 4 or 6
+14.1k How to automatically restart your crashed Golang server
+24.1k Golang : GORM read from database example
+11.8k Golang : convert(cast) string to integer value
+13.7k Golang : Fix image: unknown format error
+11.6k Golang : Sort and reverse sort a slice of runes
+15.1k Golang : invalid character ',' looking for beginning of value
+16k Golang : Get IP addresses of a domain name
+19.1k Golang : How to count the number of repeated characters in a string?
+10.6k Golang : Replace a parameter's value inside a configuration file example