How to deal with 'No such file or directory' in os.Stat

PHPz
Release: 2024-02-14 18:27:09
forward
960 people have browsed it

如何处理 os.Stat 中的“没有这样的文件或目录”

php editor Zimo brings you a guide on how to deal with the "no such file or directory" problem in os.Stat. os.Stat is a function used to obtain file or directory information, but sometimes when we try to obtain information about a non-existent file or directory, we will encounter the error "No such file or directory". In this article, we'll cover a few ways to deal with this problem to help you better handle this situation. Whether you are a beginner or an experienced developer, this article will provide you with useful solutions. Let’s take a look!

Question content

I have a piece of code that is looking for stat a file and if the file does not exist, returns some default values. That is, this code looks like this:

fileInfo, err := os.Stat(absolutePath)
if err != nil {
    if os.IsNotExist(err) {
        return <default val>, nil
    }
    return nil, fmt.Errorf(...)
}
Copy after login

To "catch" "file does not exist" errors, I read that it is recommended to use os.isnotexist to check if the error indicates that the file does not exist. However, os.isnotexist does not catch this error because the platform returns open <blah>: No such file or directory. I could add my own error handling here, but is there an idiomatic way to handle "file does not exist" errors in os calls? os.isnotexist The error checked for handling appears to be just a special case of a potential "file does not exist" error.

Workaround

If you read the documentation you will see the following:

func isnotexist

func IsNotExist(err error) bool
Copy after login

isnotexist Returns a Boolean value indicating whether the error is known Reports that the file or directory does not exist. contented errnotexist and some syscall errors.

This function precedes the error. It only supports errors returned by the os package. New code should use errors.is(err, fs.errnotexist). [emphasize. mine]

The above is the detailed content of How to deal with 'No such file or directory' in os.Stat. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
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