In Go language, determining whether a file or folder exists is a common operation, often used for file system checks or error handling. Go's standard library provides multiple methods to achieve this functionality. This article will detail these methods and help you quickly master them through code examples.
Using the os.Stat Function
The os.Stat function is the most commonly used method in Go to determine whether a file or folder exists. It returns a FileInfo object and an error value. If the file or folder does not exist, the error value will be os.ErrNotExist.
package main
import (
"fmt"
"os"
)
func main() {
path := "example.txt"
_, err := os.Stat(path)
if os.IsNotExist(err) {
fmt.Printf("File or folder %s does not exist\n", path)
} else {
fmt.Printf("File or folder %s exists\n", path)
}
}
Note: The os.Stat function may return other types of errors, such as permission issues, so it is recommended to use os.IsNotExist to precisely determine non-existence.
Using the os.Lstat Function
The os.Lstat function is similar to os.Stat, but it does not follow symbolic links. This is useful when dealing with symbolic links to avoid misjudgment.
package main
import (
"fmt"
"os"
)
func main() {
path := "symlink"
_, err := os.Lstat(path)
if os.IsNotExist(err) {
fmt.Printf("Symbolic link %s does not exist\n", path)
} else {
fmt.Printf("Symbolic link %s exists\n", path)
}
}
Distinguishing Between Files and Folders
Sometimes we need to distinguish between files and folders. By checking the IsDir method of the FileInfo object, this can be easily achieved.
package main
import (
"fmt"
"os"
)
func main() {
path := "example"
info, err := os.Stat(path)
if os.IsNotExist(err) {
fmt.Printf("%s does not exist\n", path)
} else if info.IsDir() {
fmt.Printf("%s is a folder\n", path)
} else {
fmt.Printf("%s is a file\n", path)
}
}
Warning: Avoid using functions like os.Open to check existence, as they may open files, leading to resource waste or unintended modifications.