dongzhiyi2006 2017-10-05 07:34
浏览 125
已采纳

打开文件并在另一个函数中创建NewReader后如何关闭文件?

I want the func OpenFile() to read gzip files and bzip2 files. I will add other types later.

func OpenFile(name string) io.Reader{

  file, err := os.Open(name)

  if err != nil {
   log.Fatal(err)
 }

  if(strings.Contains(name, ".gz")){

    gzip, gerr := gzip.NewReader(file)
    if gerr != nil {
        log.Fatal(gerr)
    }
    return gzip

  }else if(strings.Contains(name, ".bz2")){

    bzip2 := bzip2.NewReader(file)
    return bzip2    

  }else{
    return file     
  } 
}

I call the OpenFile() in another function A:

    in := OpenFile(p)

    for _, d := range fdb.Detect(in) {
        set[d] = true
        counter++
    }
    ...

My issue is that if I use "defer file.Close()" in OpenFile(), the file would be closed too early so I can't get any input value. How can I close the file in A?

Notice that the gzip.NewReader(file) and the bzip2.NewReader(file) return different interfaces.

gzip: func NewReader(r io.Reader) (*Reader, error) // Reader has a func Close()

bzip2: func NewReader(r io.Reader) io.Reader // io.Reader doesn't have a func Close()

This is the reason that I can't return NewReader(file) in the first place.

Thank you!

展开全部

  • 写回答

3条回答 默认 最新

  • doutuo3899 2017-10-05 08:23
    关注

    As others have mentioned, you should return an io.ReadCloser from your function. Since the return value of bzip2.NewReader() does not satisfy io.ReadCloser, you'll need to create your own type.

    type myFileType struct {
        io.Reader
        io.Closer
    }
    
    func OpenFile(name string) io.ReadCloser {
    
        file, err := os.Open(name)
    
        if err != nil {
            log.Fatal(err)
        }
    
        if strings.Contains(name, ".gz") {
    
            gzip, gerr := gzip.NewReader(file)
            if gerr != nil {
                log.Fatal(gerr)
            }
            return gzip
    
        } else if strings.Contains(name, ".bz2") {
    
            bzip2 := bzip2.NewReader(file)
            return myFileType{bzip2, file}
    
        } else {
            return file
        }
    }
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部