How to determine whether a file exists in golang

Release: 2019-12-25 09:54:53
Original
5552 people have browsed it

How to determine whether a file exists in golang

Usually before reading or writing a file, you need to determine whether the file or directory exists, otherwise certain processing methods may cause program errors. So it is best to determine whether the file exists before doing any operation.

The method for Golang to determine whether a file or folder exists is to use the error value returned by the os.Stat() function to determine:

1. If the returned error is nil, it indicates that the file or folder exists. The folder does not exist

2. If the returned error type is judged to be true using os.IsNotExist(), it means that the file or folder exists

3. If the returned error is of other types, it will not Determine whether it exists

// 判断所给路径文件/文件夹是否存在 
func Exists(path string) bool {  
    _, err := os.Stat(path)    //os.Stat获取文件信息  
    if err != nil {  
        if os.IsExist(err) {  
            return true  
        }  
        return false  
    }  
    return true  
}  
  
// 判断所给路径是否为文件夹  
func IsDir(path string) bool {  
    s, err := os.Stat(path)  
    if err != nil {  
        return false  
    }  
    return s.IsDir()  
}  
  
// 判断所给路径是否为文件  
func IsFile(path string) bool {  
    return !IsDir(path)  
}
Copy after login

Note:

When our FileExist returns true, the file does not necessarily exist.

When we do not have readable permissions for a certain part of the target path, os.Lstat and syscall.Access will also return an error, but this error will not cause os.IsNotExist to return true.

When the file does not exist and you do not have access rights to the directory where the file is located or its upper directory, FileExist will still return true, and the bug occurs at this time.

So the important point is that before judging whether the file exists, you should first judge whether you have access rights to the file and its path.

For more golang knowledge, please pay attention to the golang tutorial column.

The above is the detailed content of How to determine whether a file exists in golang. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!