Golang : How to make a file read only and set it to writable again?




Problem:

You want to set a file to read-only mode and also want to test if a file is really on read-only mode. How to do that?

Solution:

Below is my own solution ported from Java. It has 3 functions. One to set a file to read-only, one to set a file to writable and finally one function to test if a file is writable. For Linux/Unix, you need to take extra care of the os.Chmod() function where the permission is set to 0222 and 0444 ... which is inclusive of everyone. If your system or the target file has different security requirements, please modify the permission bits. See https://kb.iu.edu/d/abdb for more details.

Here you go!

setFileReadOnly.go


 package main

 import (
  "fmt"
  "log"
  "os"
 )

 func CanWrite(filepath string) (bool, error) {
  file, err := os.OpenFile(filepath, os.O_WRONLY, 0666)
  if err != nil {
 if os.IsPermission(err) {
 return false, err
 }
  }
  file.Close()
  return true, nil

 }

 func SetWritable(filepath string) error {
  err := os.Chmod(filepath, 0222)
  return err
 }

 func SetReadOnly(filepath string) error {
  err := os.Chmod(filepath, 0444)
  return err
 }

 func main() {

  if len(os.Args) != 2 {
 fmt.Printf("Usage : %s <filename>\n", os.Args[0])
 os.Exit(0)
  }

  filename := os.Args[1]

  fmt.Printf("Set %s to read only mode\n", filename)
  err := SetReadOnly(filename)

  if err != nil {
 log.Fatal(err)
  }

  // test after set to READ ONLY
  result, err := CanWrite(filename)
  if err != nil {
 //fmt.Println(err) -- permission denied because of readonly
  }
  fmt.Printf("Is %s writable? : [%v]\n", filename, result)

  fmt.Println("Set", filename, " to writable")
  err = SetWritable(filename)
  if err != nil {
 log.Fatal(err)
  }

  // test after set to WRITE ONLY
  result, err = CanWrite(filename)
  if err != nil {
 fmt.Println(err)
  }
  fmt.Printf("Is %s writable? : [%v]\n", filename, result)
 }

Test result on Linux:

$ ./setFileReadOnly readonly.txt

Set readonly.txt to read only mode

Is readonly.txt writable? : [false]

Set readonly.txt to writable

Is readonly.txt writable? : [true]

On Windows, the target file Read-only attributes( in Property window box) will be toggled to ticked when set to read only mode and "un-ticked" when set to writable mode.

Happy coding!

References:

https://kb.iu.edu/d/abdb

https://www.socketloop.com/tutorials/golang-test-file-read-write-permission-example

https://www.socketloop.com/tutorials/golang-change-file-read-or-write-permission-example

  See also : Golang : How to check if a file is hidden?





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