Golang "Access is denied" error on trying to write to file with io.WriteString
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)
Related videos on Youtube
David Thien
Updated on June 04, 2022Comments
-
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 over 8 yearsDo the
os.Open
method fail ? You don't check the error in you example...
-
-
David Thien over 8 yearsThanks for the info! That must be why I couldn't find the error, because I was always searching for os.Open.
-
David Thien over 8 yearsThanks for the help, I hadn't realized what sort of issue it was.