英文:
Golang "Access is denied" error on trying to write to file with io.WriteString
问题
我目前正在运行的是64位的Windows 8,并且我正在尝试为一个Web服务器创建一个日志文件。相关的代码如下:
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")
}
每当调用io.WriteString
时,返回的错误是write log/visit.log: Access is denied.
我已经在我的系统上安装了Go,并且我正在使用go run x.go
来运行我的Go源代码。
英文:
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.
答案1
得分: 8
我相信你是以只读模式打开文件。你可以尝试使用os.OpenFile而不是os.Open,并根据https://stackoverflow.com/questions/13513375/how-to-append-text-to-a-file-in-golang和https://stackoverflow.com/questions/7151261/append-to-a-file-in-go中的示例,使用适当的标志进行操作。
英文:
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 https://stackoverflow.com/questions/13513375/how-to-append-text-to-a-file-in-golang and https://stackoverflow.com/questions/7151261/append-to-a-file-in-go
答案2
得分: 2
从文档中可以看出,你有一个只读文件:
> Open
打开指定的文件以供读取...
你需要使用 os.OpenFile
函数,并使用适当的标志。
一些示例
写入文件的常见方法(由 ioutil.WriteFile
使用):
f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
创建或追加到文件:
f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_APPEND, perm)
仅追加到现有文件:
f, err := os.OpenFile(filename, os.O_WRONLY|os.O_APPEND, perm)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论