duanrenzou1619 2017-07-14 14:59
浏览 93
已采纳

为什么打开目录时os.Open返回nil错误?

I've spend some time looking for an error in my code and it appeared that at one place I was trying to read contents of a directory like it was the file. Consider the following code:

import (
    "fmt"
    "os"
)

func init() {
    file, err := os.Open("/tmp/")
    fmt.Println(file, err) //err == nil here
    var b []byte
    n, err := file.Read(b)
    fmt.Println(n, err) //err == "read /tmp/: is a directory"
}

I am wondering, why os.Open allows to 'open' a directory without an error if I cannot 'read' it anyway? The documentation says

Open opens the named file for reading. If successful, methods on the returned file can be used for reading; the associated file descriptor has mode O_RDONLY. If there is an error, it will be of type *PathError. [reference]

If the 'directory' is a 'file' is disputable but for me it looks a bit misleading. Is there any usage for that behavior?

  • 写回答

1条回答 默认 最新

  • doujia1679 2017-07-14 15:03
    关注

    "Reading" has more meanings, one of which is reading the contents of a file.

    Another meaning is if the file denotes a directory, you may read its content, which is the list of the files / subfolders in it, using File.Readdir() or File.Readdirnames(). This is perfectly valid for an opened file whose name denotes a directory.

    Also you may do a lot more with an opened os.File even if it denotes a folder, e.g. call its File.Chdir() (exclusive for directories) or File.Chmod() methods, or get statistics about it using File.Stat(). I don't see why "opening" a folder should be disallowed. The wording in the doc may not be perfect (or it could be extended to mention this though).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度