@kjk1/

gobook file exists

Go

No description

fork
loading
Files
  • main.go

This Plugin Crashed!

Error: Error: must not create an existing file {"type":"CREATE_FILE","wid":"0.5937528886467416","path":"main.go","file":{"path":"main.go","content":{"asEncoding":{"base64":"Ly8gbm8gcGxheWdyb3VuZApwYWNrYWdlIG1haW4KCmltcG9ydCAoCgkiZm10IgoJIm9zIgopCgovLyA6c2hvdyBzdGFydAoKLy8gSXNQYXRoeGlzdHMgcmV0dXJucyB0cnVlIGlmIGEgZ2l2ZW4gcGF0aCBleGlzdHMsIGZhbHNlIGlmIGl0IGRvZXNuJ3QuCi8vIEl0IG1pZ2h0IHJldHVybiBhbiBlcnJvciBpZiBlLmcuIGZpbGUgZXhpc3RzIGJ1dCB5b3UgZG9uJ3QgaGF2ZQovLyBhY2Nlc3MKZnVuYyBJc1BhdGh4aXN0cyhwYXRoIHN0cmluZykgKGJvb2wsIGVycm9yKSB7CglfLCBlcnIgOj0gb3MuTHN0YXQocGF0aCkKCWlmIGVyciA9PSBuaWwgewoJCXJldHVybiB0cnVlLCBuaWwKCX0KCWlmIG9zLklzTm90RXhpc3QoZXJyKSB7CgkJcmV0dXJuIGZhbHNlLCBuaWwKCX0KCS8vIGVycm9yIG90aGVyIHRoYW4gbm90IGV4aXN0aW5nIGUuZy4gcGVybWlzc2lvbiBkZW5pZWQKCXJldHVybiBmYWxzZSwgZXJyCn0KCmZ1bmMgcHJpbnRFeGlzdHMocGF0aCBzdHJpbmcpIHsKCWV4aXN0cywgZXJyIDo9IElzUGF0aHhpc3RzKHBhdGgpCglpZiBlcnIgPT0gbmlsIHsKCQlmbXQuUHJpbnRmKCJGaWxlICclcycgZXhpc3RzOiAldlxuIiwgcGF0aCwgZXhpc3RzKQoJfSBlbHNlIHsKCQlmbXQuUHJpbnRmKCJJc0ZpbGVFeGlzdHMoJyVzJykgZmFpbGVkIHdpdGggJyVzJ1xuIiwgcGF0aCwgZXJyKQoJfQp9CmZ1bmMgbWFpbigpIHsKCXByaW50RXhpc3RzKCJtYWluLmdvIikKCXByaW50RXhpc3RzKCJub24tZXhpc3RlbnQtZmlsZS50eHQiKQp9CgovLyA6c2hvdyBlbmQ="},"asBuffer":null},"loaded":true}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// no playground
package main

import (
	"fmt"
	"os"
)

// :show start

// IsPathxists returns true if a given path exists, false if it doesn't.
// It might return an error if e.g. file exists but you don't have
// access
func IsPathxists(path string) (bool, error) {
	_, err := os.Lstat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	// error other than not existing e.g. permission denied
	return false, err
}

func printExists(path string) {
	exists, err := IsPathxists(path)
	if err == nil {
		fmt.Printf("File '%s' exists: %v\n", path, exists)
	} else {
		fmt.Printf("IsFileExists('%s') failed with '%s'\n", path, err)
	}
}
func main() {
	printExists("main.go")
	printExists("non-existent-file.txt")
}

// :show end