Golang io method to read files and determine whether files exist

Release: 2019-12-05 16:10:43
Original
3305 people have browsed it

Golang io method to read files and determine whether files exist

one. To determine whether a file exists, you need to use two functions in the "os" package: os.Stat() and os.IsNotExit()

func (f *File) Stat() (fi FileInfo, err error)
Copy after login

Stat returns a FileInfo type value describing file f. If an error occurs, the underlying error type is *PathError.

func IsNotExist(err error) bool
Copy after login

Returns a Boolean value indicating whether the error indicates that a file or directory does not exist. ErrNotExist and some system call errors will return true.

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 exists

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

3. If the returned error is of other types, it does not Determine whether there is

func PathExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}
Copy after login

The code can be simplified:

if _, err := os.Stat(path); 
 os.IsNotExist(err){
        return err
    }
Copy after login

2. To read the contents of the file, you need to use the "io/ioutil" package

fileContent, err := ioutil.ReadFile(load)
	if err != nil {
		log.Panic(err)
	}
Copy after login

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

The above is the detailed content of Golang io method to read files and determine whether files exist. 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!