【问题标题】:Golang "Access is denied" error on trying to write to file with io.WriteString尝试使用 io.WriteString 写入文件时出现 Golang“访问被拒绝”错误
【发布时间】:2015-11-05 05:02:45
【问题描述】:

我目前正在运行 Windows 8 64 位,并且我正在尝试创建一个用于 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 源代码。

【问题讨论】:

  • os.Open 方法是否失败?您没有检查示例中的错误...

标签: file go io


【解决方案1】:

我相信您正在以只读模式打开文件。您可以尝试使用 os.OpenFile 来代替 os.Open,使用适当的标志,如 How to append text to a file in golang?Append to a file in Go 所示

【讨论】:

  • 感谢您的帮助,我还没有意识到这是什么问题。
【解决方案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)

【讨论】:

  • 感谢您的信息!这一定是我找不到错误的原因,因为我一直在搜索 os.Open。​​
猜你喜欢
  • 2019-06-21
  • 2015-03-06
  • 1970-01-01
  • 2011-11-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-14
相关资源
最近更新 更多