Unless you are using a method such as OpenFile(), it is good to ensure that the file you wish to use exists; otherwise, it may lead to unexpected errors.
In this article, we will need the os package from the Go standard library to check if a file exists before using it.
Golang Stat Method
We can use the Golang Stat() method to check if a file exists or not. The syntax of the function is as shown:
The function takes the name of the file as the argument and returns the file information as an object (if the file exists) or an error.
Keep in mind that the Stat method can encounter many errors. Hence, we need to check if it is a file that does not exist error. We can do this using the os.ErrNotExist() error.
Consider the example code shown below:
import (
"errors"
"fmt"
"log"
"os"
)
func main() {
_, err := os.Stat("hello.txt")
if errors.Is(err, os.ErrNotExist) {
log.Fatal("File does not exist")
} else {
fmt.Println("file exists")
}
}
Once we run the code above, it should check if the file exists in the provided path. We check if the file exists in the current directory in our example.
The program above should return:
file exists
If we specify a file that does not exist, the output is as shown:
exit status 1
If you want to display any other error other than the “File does not exist” error, we can do:
import (
"errors"
"fmt"
"log"
"os"
)
func main() {
_, err := os.Stat("hellotxt")
if err != nil {
log.Fatal(err)
}
if errors.Is(err, os.ErrNotExist) {
log.Fatal("File does not exist")
} else {
fmt.Println("file exists")
}
}
Conclusion
This guide showed you how to check if a file exists before using it. This can help prevent a fatal error in your program.