Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于"临时文件和目录"无法删除tempfile #93

Open
zmc-x opened this issue Apr 17, 2023 · 1 comment
Open

关于"临时文件和目录"无法删除tempfile #93

zmc-x opened this issue Apr 17, 2023 · 1 comment

Comments

@zmc-x
Copy link

zmc-x commented Apr 17, 2023

问题描述:
执行"临时文件和目录"代码时,会存在这样的error:The process cannot access the file because it is being used by another process.
首先代码如网站描述:

func check(e error) {
    if e != nil {
        panic(e)
    }
}

func main() {

    f, err := os.CreateTemp("", "sample")
    check(err)

    fmt.Println("Temp file name:", f.Name())

    defer os.Remove(f.Name())

    _, err = f.Write([]byte{1, 2, 3, 4})
    check(err)
}

在这个过程中并不能删掉所创建的临时文件,因为此时*File未关闭(造成存在一个process 正在访问file),导致os.Remove()无法访问,进行删除。
故应该修改为:

func check(e error) {
    if e != nil {
        panic(e)
    }
}

func main() {

    f, err := os.CreateTemp("", "sample")
    check(err)

    fmt.Println("Temp file name:", f.Name())

    defer os.Remove(f.Name())
    defer f.Close()
    _, err = f.Write([]byte{1, 2, 3, 4})
    check(err)
}
@945725631
Copy link

cc

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants