January 2018
Intermediate to advanced
340 pages
8h 6m
English
Checking whether a file exists is a two-step process. First, os.Stat() must be called on the file to get FileInfo. If the file does not exist, then a FileInfo struct is not returned, but an error is returned. There are multiple errors that os.Stat() might return, so the error type must be inspected. The standard library provides a function called os.IsNotExist() that will inspect an error to see whether it was caused because a file does not exist.
The following example will call log.Fatal() if the file does not exist, but you can handle the error gracefully and move on without exiting if desired:
package main import ( "log" "os" ) func main() { // Stat returns file info. It will return // an error if there is ...Read now
Unlock full access