dongmen9517 2018-08-24 07:30
浏览 143

File.Readdir()不能被多次调用?

When i study Golang, I write the code bellow:

list1,_ := f.Readdir(-1)
len(list1) //some value

list2,_ := f.Readdir(-1)
len(list2) //0

When os.File's method Readdir() called more than once, it will always return an empty []FileInfo.

I want to know why? And how to make my code work?

  • 写回答

1条回答 默认 最新

  • doulang2311 2018-08-24 07:33
    关注

    According to Golang spec for Readdir:

    If n > 0, Readdir returns at most n FileInfo structures. In this case, if Readdir returns an empty slice, it will return a non-nil error explaining why. At the end of a directory, the error is io.EOF.

    It is returning empty because you have reached the file end EOF. If you want to read the same file again. You should move the pointer to the start of the file to read it again.

    list1,_ := f.Readdir(-1)
    len(list1) //some value
    
    if _, err := f.Seek(0, 0); err != nil { // seek to the start of the file
        panic(err)
    }
    
    list2,_ := f.Readdir(-1)
    len(list2) // will not return 0
    

    Seeking the file pointer is easy:

    func (f *File) Seek(offset int64, whence int) (ret int64, err error)
    

    Seek sets the offset for the next Read or Write on file to offset, interpreted according to whence: 0 means relative to the origin of the file, 1 means relative to the current offset, and 2 means relative to the end. It returns the new offset and an error, if any.

    评论

报告相同问题?

悬赏问题

  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入
  • ¥20 XP系统在重新启动后进不去桌面,一直黑屏。
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥15 无线移动边缘计算系统中的系统模型
  • ¥15 深度学习中的画图问题
  • ¥15 java报错:使用mybatis plus查询一个只返回一条数据的sql,却报错返回了1000多条
  • ¥15 Python报错怎么解决
  • ¥15 simulink如何调用DLL文件