Last active
November 10, 2022 02:10
-
-
Save gammazero/c689fe224c39e9aa7e110accbe4de999 to your computer and use it in GitHub Desktop.
Check if files and directories exist
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func fileExists(filename string) bool { | |
_, err := os.Stat(filename) | |
return !errors.Is(err, fs.ErrNotExist) | |
} | |
func dirExists(name string) (bool, error) { | |
fi, err := os.Stat(name) | |
if err != nil { | |
if errors.Is(err, fs.ErrNotExist) { | |
return false, nil | |
} | |
return false, err | |
} | |
if !fi.IsDir() { | |
return false, fmt.Errorf("%s is not a directory", name) | |
} | |
return true, nil | |
} | |
func dirEmpty(name string) (bool, error) { | |
f, err := os.Open(name) | |
if err != nil { | |
return false, err | |
} | |
defer f.Close() | |
_, err = f.Readdirnames(1) | |
if err == io.EOF { | |
return true, nil | |
} | |
return false, err | |
} | |
func fileChanged(filePath string, modTime time.Time) (time.Time, bool, error) { | |
fi, err := os.Stat(filePath) | |
if err != nil { | |
return modTime, false, err | |
} | |
if fi.ModTime() != modTime { | |
return fi.ModTime(), true, nil | |
} | |
return modTime, false, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment