是否需要关闭文件? [英] Does the file need to be closed?

查看:93
本文介绍了是否需要关闭文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用golang杜松子酒,我使用以下命令读取文件数据:

Using golang gin, I read file data using:

file, fileHeader, err:=ctx.Request.FormFile("blabla...")

我需要写这个吗?

defer file.Close()

我跳到源代码,上面写着:

I jump to the source code, it says:

// Open opens and returns the FileHeader's associated File.
func (fh *FileHeader) Open() (File, error) {
        if b := fh.content; b != nil {
                r := io.NewSectionReader(bytes.NewReader(b), 0, int64(len(b)))
                fmt.Printf("TODDLINE:152\n")
                fmt.Printf("TODDLINE:154:fmpfile:%#v\n", fh.tmpfile)
                fmt.Printf("TODDLINE:154:Filename:%#v\n", fh.Filename)
                return sectionReadCloser{r}, nil
        }
        fmt.Printf("TODDLINE:155\n")
        return os.Open(fh.tmpfile)
}

如果它使用os.Open,我想我必须关闭文件,但是如果它重新调整了部分ReadCloser {r},则Close函数显示如下:

If it uses os.Open, I guess I must close the file, but if it retuns the sectionReadCloser{r}, the Close function shows like this:

func (rc sectionReadCloser) Close() error {
        return nil
}

seciontReadCloser的关闭功能不执行任何操作. 而且我发现它确实返回了部分ReadCloser {r}. 我想我应该关闭文件,但是我仍然想知道什么时候它将返回os.Open.我将继续阅读源代码并尝试理解它.如果有人给我一些建议,那就太好了.

The close function of seciontReadCloser doesn't do anything. And I find that it does return the sectionReadCloser{r}. I guess I should close the file, but I still want to know when it will return the os.Open. I will keep going to read the source code and try to understand it. It would be nice if someone gives me some advice.

推荐答案

如果返回的file实现了io.Closer(即,如果它具有Close方法),则除非文档中规定,否则您有责任关闭它明确指出否则.

If the file returned implements io.Closer (i.e., if it has a Close method), assume you are responsible for closing it unless the documentation explicitly states otherwise.

这篇关于是否需要关闭文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆