duanrenzou1619
2017-07-14 14:59
浏览 92

为什么打开目录时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?

图片转代码服务由CSDN问答提供 功能建议

我花了一些时间在代码中查找错误,看来我在一个地方试图 读取目录内容就像文件一样。 考虑以下代码:

  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 ==“读取/ tmp /:是目录” 
} 
   
 
 

我想知道为什么是 os。 如果我仍然无法“读取”目录,打开允许“打开”目录而不会出现错误? 文档说

Open打开指定的文件进行读取。 如果成功,则可以使用 返回文件中的方法进行读取; 关联的文件描述符 的模式为O_RDONLY。 如果有错误,则类型为 * PathError。 [参考]

如果“目录”是“文件”是有争议的,但对我来说,这似乎有点误导。 这种行为有什么用吗?

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

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).

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题