In golang, os.OpenFile does not return os.ErrNotExist if the file does not exist

I am trying to open a file and I would like to know if it does not exist in order to respond. But a mistake

os.OpenFile(fName, os.O_WRONLY, 0600) 

returns when the file does not exist, different from os.ErrNotExists

 os.ErrNotExists -> "file does not exist" err.(*os.PathError).Err -> "no such file or directory" 

os.Stat also returns the same error if the file is not there. Is there a predefined error that I can compare with, instead of doing it manually?

+7
go error-handling
source share
1 answer

Os package

func IsExist

 func IsExist(err error) bool 

IsExist returns a boolean value indicating whether the error is known; report that the file or directory already exists. He is satisfied with ErrExist, as well as some syscall errors.

func IsNotExist

 func IsNotExist(err error) bool 

IsNotExist returns a boolean value indicating whether the error is known; report that the file or directory does not exist. He is satisfied with ErrNotExist, as well as some syscall errors.

Use the os.IsNotExist function. For example,

 package main import ( "fmt" "os" ) func main() { fname := "No File" _, err := os.OpenFile(fname, os.O_WRONLY, 0600) if err != nil { if os.IsNotExist(err) { fmt.Print("File Does Not Exist: ") } fmt.Println(err) } } 

Output:

 File Does Not Exist: open No File: No such file or directory 
+11
source share

All Articles