Home >Backend Development >Golang >How to Check if a File or Directory Exists in Go?

How to Check if a File or Directory Exists in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-12-03 07:26:13284browse

How to Check if a File or Directory Exists in Go?

How to verify the existence of a file or directory in Go

In many programming scenarios, it becomes necessary to verify if a particular file or directory exists before proceeding with further operations. Go provides a simple and efficient way to perform this check.

To determine the existence of a file or directory, the os.Stat function can be leveraged. This function takes a path as its parameter and returns a FileInfo object which contains information about the file or directory.

To check for existence, the following code can be utilized:

import (
    "os"
)

func exists(path string) (bool, error) {
    _, err := os.Stat(path)
    if err == nil {
        return true, nil
    } else if os.IsNotExist(err) {
        return false, nil
    }
    return false, err
}

This function returns a boolean indicating the existence of the file or directory and an error if encountered. The usage of os.IsNotExist allows for distinguishing between non-existing files or directories and other potential errors that may arise during the stat operation.

The above is the detailed content of How to Check if a File or Directory Exists 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