我正在Vimscript中寻找一种优雅的方法来检查函数中当前目录中是否存在文件.
我想出了这个,但不确定这是否是最优雅的解决方案(我将设置vim选项,如果它存在) - 是否有任何方法不必再进行文件名的比较 - 可能使用不同的__CODE__内置函数( ?):
:function! SomeCheck()
: if findfile("SpecificFile", ".") == "SpecificFile"
: echo "SpecificFile exists"
: endif
:endfunction
Run Code Online (Sandbox Code Playgroud)
ste*_*anB 128
通过一些搜索,vim man我发现了这个,看起来比原来好多了:
:function! SomeCheck()
: if filereadable("SpecificFile")
: echo "SpecificFile exists"
: endif
:endfunction
Run Code Online (Sandbox Code Playgroud)
bri*_*rns 49
一些评论表达了对filereadable使用的关注和使用glob.这解决了存在确实存在的文件的问题,但权限阻止了它被读取.如果要检测此类情况,以下内容将起作用:
:if !empty(glob("path/to/file"))
: echo "File exists."
:endif
Run Code Online (Sandbox Code Playgroud)
如果文件可读(expand(“〜/ .vim / bundle / vundle / README.md”)),则让g:hasVundle = 1 endif
filereadable是必需的,但expand如果您~在自己的路径中使用,则还有一个额外的方便步骤:
:function! SomeCheck()
: if filereadable(expand("SpecificFile"))
: echo "SpecificFile exists"
: endif
:endfunction
Run Code Online (Sandbox Code Playgroud)
例如
:echo filereadable('~/.vimrc')给0,:echo filereadable(expand('~/.vimrc')) 给 1小智 6
抱歉,如果为时已晚,但正在做
if !empty(expand(glob("filename")))
echo "File exists"
else
echo "File does not exists"
endif
Run Code Online (Sandbox Code Playgroud)
对我来说效果很好