Home >Backend Development >Golang >How Do I Check for File or Directory Existence in Go?

How Do I Check for File or Directory Existence in Go?

Susan Sarandon
Susan SarandonOriginal
2024-12-05 18:33:111031browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn