golang

Golang Check if File Exists

As programmers, we encounter instances where we need to work with files. We could be reading or writing to a file in the system.

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:

func Stat(name string) (FileInfo, error)

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:

package main
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:

$ go run check_file_exists.go
file exists

If we specify a file that does not exist, the output is as shown:

File does not exist
exit status 1

If you want to display any other error other than the “File does not exist” error, we can do:

package main
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.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list