Golang reads whether the file exists

Release: 2020-03-27 10:32:40
Original
2709 people have browsed it

Golang reads whether the file exists

Determining whether a file exists is a very common requirement, and there are many solutions to achieve this function in golang.

Cross-platform implementation

The idea of ​​cross-platform implementation is very simple. If a file does not exist, then using os.Lstat will definitely return an error. Just judge the error It just means that the file does not exist.

Perhaps you have noticed that some codes use os.Open to complete the above work, but it is best not to do this, because although there is no difference in the functions completed by the two, the calling overhead of open and stat is different. The latter is smaller than the former, and for determining whether a file exists, it makes more sense to check its metadata than to directly try to open it.

Then let’s take a look at the implemented code:

func FileExist(path string) bool {
  _, err := os.Lstat(path)  
return !os.IsNotExist(err)
}
Copy after login

POSIX platform implementation

If your program is for POSIX platform (such as UNIX, Linux etc.), then there is a simpler solution - syscall.Access.

syscall.Access provides a means for users to check file metainformation. It is usually used to check file permissions and the existence of files.

Check the file by using the syscall.F_OK flag. If it does not exist, the same error as os.Lstat will be returned:

func FileExist(path string) bool {
  err := syscall.Access(path, syscall.F_OK)
  return !os.IsNotExist(err)
}
Copy after login

The biggest advantage of this implementation is that it is simple and intuitive, but it Not available on Windows.

For more golang knowledge, please pay attention to the golang tutorial column on the PHP Chinese website.

The above is the detailed content of Golang reads whether the file exists. 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!