dongzhiyi2006 2017-10-05 15: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 16: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条)

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据