Vimscript: how to determine if a specific file exists

I am looking for an elegant way in vimscript to check if a file exists in the current directory in a function.

I came up with this, but I'm not sure if this is the most elegant solution (I will set the vim option if it exists) - is there a way to not do another file name comparison - maybe use different vim built-in function (?):

 :function! SomeCheck() : if findfile("SpecificFile", ".") == "SpecificFile" : echo "SpecificFile exists" : endif :endfunction 
+74
vim file-exists
Jun 23 2018-10-06T00:
source share
2 answers

With a bit of searching in vim man I found this that looks a lot better than the original:

 :function! SomeCheck() : if filereadable("SpecificFile") : echo "SpecificFile exists" : endif :endfunction 
+104
Jun 23 2018-10-10T00:
source share

Some comments express concern about filereadable and use glob instead. This concerns the problem of having a file that exists, but permissions prevent it from being read. If you want to detect such cases, the following will work:

 :if !empty(glob("path/to/file")) : echo "File exists." :endif 
+31
May 6 '14 at
source share



All Articles