Home >Backend Development >Golang >How Do I Check for File or Directory Existence in Go?
Checking File or Directory Existence in Go
Checking the existence of a file or directory is a common task in programming. In Go, there are a couple of ways to approach this.
One method is to use the os.Stat() function. This function returns a FileInfo object, which contains information about the file or directory, including whether it exists. The following code shows how to use os.Stat() to check for the existence of a file or directory:
import "os" func exists(path string) bool { if _, err := os.Stat(path); err != nil { if os.IsNotExist(err) { return false } return false } return true }
Another method is to use the Open() function with the O_RDONLY flag. This flag opens the file or directory in read-only mode, and it returns an os.File object. If the file or directory does not exist, the function will return an error. The following code shows how to use Open() to check for the existence of a file or directory:
import "os" func exists(path string) bool { f, err := os.OpenFile(path, os.O_RDONLY, 0666) if err != nil { if err == os.ErrNotExist { return false } return false } f.Close() return true }
The above is the detailed content of How Do I Check for File or Directory Existence in Go?. For more information, please follow other related articles on the PHP Chinese website!