I am working on this sample code shown below (using GO 1.22.2).
package main
import (
"bytes"
"fmt"
"io"
"log"
"os"
)
func main() {
data := []byte("This is some sample data.")
tmpFile, err := os.CreateTemp("", "example-*.txt")
if err != nil {
fmt.Println("Error creating temporary file:", err)
return
}
tName := tmpFile.Name()
defer log.Println(os.Remove(tName))
_, err = io.Copy(tmpFile, bytes.NewReader(data))
if err != nil {
fmt.Println("Error copying data to temporary file:", err)
return
}
tmpFile.Close()
f, er := os.Stat(tName)
fmt.Println("Error:", er)
}
But, when executed, I found 2 issues on windows and linux.
In Windows, I get error(syscall.Errno) internal/syscall/windows.ERROR_SHARING_VIOLATION (32)
and remove C:UserstestAppDataLocalTempexample-359410521.txt: The process cannot access the file because it is being used by another process
, at the end of the program execution
In Linux (Ubuntu), I get Error: stat /tmp/example-4163469138.txt: no such file or directory
where the file is deleting as soon as the defer line is executed, where the os.stat()
couldn’t find the file.
why does defer calls os.remove
right away in linux and not in windows?
I understand, os.remove
works differently in Linux and windows. How can I prevent these errors