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
+15.9k Golang : Get future or past hours, minutes or seconds
+4.4k Unix/Linux/MacOSx : How to remove an environment variable ?
+6.8k Golang : Check from web if Go application is running or not
+14.2k Golang : Delete certain files in a directory
+16.1k Golang : How to remove certain lines from a file
+5k Golang : How to write backslash in string?
+81.3k Golang : How to convert character to ASCII and back
+14.1k Golang : How do I get the local IP (non-loopback) address ?
+9.8k Golang : Removes punctuation or defined delimiter from the user's input
+6.8k Javascript : How to check a browser's Do Not Track status?
+18k Golang : How to run your code only once with sync.Once object
+18.3k Golang : Archive directory with tar and gzip