Golang "Access is denied" error on trying to write to file with io.WriteString

11,798

Solution 1

I believe you are opening the file in read only mode. Instead of os.Open you might try os.OpenFile with the appropriate flags as shown at How to append text to a file in golang? and Append to a file in Go

Solution 2

From the documentation, you have a read-only file:

Open opens the named file for reading...

You need to use os.OpenFile with the appropriate flags

Some examples

The common method for writing a file (used by ioutil.WriteFile):

f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)

To create or append to a file:

f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, perm)

To append only to an existing file:

f, err := os.OpenFile(filename, os.O_WRONLY|os.O_APPEND, perm)
Share:
11,798

Related videos on Youtube

David Thien
Author by

David Thien

Updated on June 04, 2022

Comments

  • David Thien
    David Thien almost 2 years

    I am currently running Windows 8 64-bit and I am trying to create a logging file for use with a web server. The code in question is:

    func LogWebPath(requestedURL string, accessedURL string, logFile string) error {
    
    file, _ := os.Open(logFile)
    _, err = io.WriteString(file, requestedURL + ":" + accessedURL)
    if(err != nil) {
      fmt.Println(err)
      return err
    }
    file.Close()
    return errors.New("nil")
    }
    

    Whenever io.WriteString is called, the error returned is write log/visit.log: Access is denied.

    I have Go installed on my system and I am using go run x.go to run my Go source.

    • Elwinar
      Elwinar over 8 years
      Do the os.Open method fail ? You don't check the error in you example...
  • David Thien
    David Thien over 8 years
    Thanks for the info! That must be why I couldn't find the error, because I was always searching for os.Open.
  • David Thien
    David Thien over 8 years
    Thanks for the help, I hadn't realized what sort of issue it was.