How to discard os.Create(file)?


(cinematik) #1

There is a code

func process() {
	// open file to write
	f, err := os.Create(fName)
	if err != nil {
		fmt.Println(err)
		f.Close()
		return
	}
	defer f.Close()
	if true {
	    //for some reason we need to discard file creation
	    //if to delete file from this line will then `defer` be executed? 
	   return
	}
	...
}

Maybe there is a better aproach to discard file creaton?


(Johan Dahl) #2

f.Close() returns an error if you have already closed the file but you can ignore this error.


(cinematik) #3

I foud out that I must explicitely execute f.Close() before deleting the file because in other case I get “the file cann’t be deleted because it used by another process”.