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
+22.9k Golang : Print out struct values in string format
+11k Golang : How to use if, eq and print properly in html template
+12k Golang : Flush and close file created by os.Create and bufio.NewWriter example
+7.3k Golang : Rename part of filename
+19.4k Golang : Set or Add HTTP Request Headers
+15.6k Golang : Read large file with bufio.Scanner cause token too long error
+6.1k Unix/Linux : Use netstat to find out IP addresses served by your website server
+12.4k Swift : Convert (cast) Int or int32 value to CGFloat
+4.5k Linux/MacOSX : How to symlink a file?
+11.1k Golang : Post data with url.Values{}
+9.9k Golang : Use regular expression to get all upper case or lower case characters example
+13.1k Golang : Generate Code128 barcode