https://codeeval.dev/gist/ef21b4629b5650feda628b673e0cb5e5
Instead of os.Stat
we can also use os.Lstat
. The difference is that os.Stat
follows symbolic links and os.Lstat
doesn’t.
In other words: for a symbolic link os.Lstat
returns information about link and os.Stat
about the file that it links to.
https://codeeval.dev/gist/f3200e74ea0cb6cb456b2c973c7bd9ce
https://codeeval.dev/gist/076b9dc06c9fa4db02a52c8c3ec828e8
Checking if a file exists is surprisingly tricky and it’s impossible to write a generic function that handles all the nuances.
Here are decisions we made:
IsDir()
on result of os.Lstat
os.Lstat
so we test the link. We could also use os.Stat
to resolve the symbolic linkos.Lstat
. Do we want to distinguish between “file doesn’t exist” and “file exists and we don’t have access”? We decided to be more informative but in some cases it would be simpler to just return a bool and always return false if os.Lstat
failspath := "foo.txt"
err := os.Remove(path)
if err != nil {
if os.IsNotExist(err) {
fmt.Printf("os.Remove failed because file doesn't exist\\n")
} else {
fmt.Printf("os.Remove failed with '%s'\\n", err)
}
}
os.Remove
returns an error for files that don’t exist.
Usually you want to ignore such errors which you can do by testing error with os.IsNotExist(err)
.
oldPath := "old_name.txt"
newPath := "new_name.txt"
err := os.Rename(oldPath, newPath)
if err != nil {
fmt.Printf("os.Rename failed with '%s'\\n", err)
}